如何链接链表中的不同节点并遍历它

时间:2014-02-28 15:23:05

标签: c algorithm data-structures linked-list nodes

我是链接列表的初学者。我有一种情况,即在终端处获取链接的大小,然后读取要保存在freq中的所有数据(在我的代码中它是“freq”但通常称为数据/信息),并使用它们创建链接列表

我到目前为止所做的工作在下面的代码中显示,该代码只读取要创建的LL的大小,并为每个输入的数据创建节点。现在我必须如何链接这些节点,使得元素首先指向其他最后将具有NULL的元素。现在我在每个创建的节点的下一个中都有NULL。

这是我的代码:

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include <string.h>

struct node
{
 int freq;
 struct node *next;
};
typedef struct node node;
node *tree=NULL;

main()
{
int size,data;

printf("enter the size of node\n");
scanf("%d", &size);
printf("start entering the number of elements until your size\n");
node *prev;
 node *temp;
prev = NULL;
do
{
 scanf("%d\n", &data);

 temp = (node*)malloc(sizeof(node));
 temp->freq=data;
 temp->next=NULL;
 if (prev)
    prev->next = temp;
 else
    tree = temp;
 prev = temp;
 size--;
}
while(size>0);

node *temp1;
temp1=temp;
while(temp1->next!=NULL)
{
  printf("%d-> ",temp->freq);
  temp1=temp1->next;
}
}

Que(1):我试图链接在终端上获取的这些节点,但它仍然不打印遍历链表。问题出在哪里?

The output is:
hp@ubuntu:~/Desktop/Internship_Xav/Huf_pointer$ ./ll 
enter the size of node
4
start entering the number of elements until your size
22
11
4
5
6//It don't print the linked list here
hp@ubuntu:~/Desktop/Internship_Xav/Huf_pointer$ 

2 个答案:

答案 0 :(得分:1)

您必须跟踪上一次迭代中添加的节点,以便您可以使前一个节点next字段指向新节点。像这样:

printf("start entering the number of elements until your size\n");
node *prev;
prev = NULL;
do
{
 scanf("%d\n", &data);
 node *temp;
 temp = (node*)malloc(sizeof(node));
 temp->freq=data;
 temp->next=NULL;
 if (prev)
    prev->next = temp;
 else
    tree = temp;
 prev = temp;
 size--;
}
while(size>0);

请注意,在第一次迭代中,这会将tree设置为新分配的节点。如果要在创建列表后遍历列表,则必须执行此操作。在循环结束时,head指向第一个元素,最后一个元素的next指向NULL

是的,您遍历列表的方法是正确的。

<强>更新

您描述的遍历列表的方法是正确的,但您没有正确实现它。

您希望从列表的头部开始,而不是从temp开始,因为temp是您分配的最后一个节点。条件不是while (temp1->next != NULL),循环将永远不会执行,因为temp1是最后一个节点,而最后一个节点的next字段始终指向NULL

相反,这就是你想要的:

node *temp1;
temp1 = tree;
while(temp1 != NULL)
{
  printf("%d-> ", temp1->freq);
  temp1 = temp1->next;
}

请注意,printf()的参数也发生了变化,您传递了temp->freq,正确的变量将是temp1->freq

答案 1 :(得分:0)

只需跟踪上一个节点并将其链接到下一个节点。

node *temp,*temp2=NULL,*head;
do
{
 scanf("%d", &data);

 temp = (node*)malloc(sizeof(node));
 if (temp2==NULL)
   head=temp;
 else
   temp2->next=temp;

 temp->freq=data;
 temp->next=NULL;
 temp2=temp;

 size--;
}while(size>0);

head将给出链表的起始节点。

此外,您可能希望scanf("%d", &data);代替scanf("%d\n", &data);。请参阅this answer