繁体   English   中英

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

[英]How to link different nodes in linked list and traverse it

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

到目前为止,我所做的工作显示在下面的代码中,该代码仅读取要创建的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$ 

您将必须跟踪上一次迭代中添加的节点,以便可以使上一个节点的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

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

UPDATE

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

您想从列表的开头而不是从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

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

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); 看到这个答案

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM