【发布时间】:2016-02-13 19:41:23
【问题描述】:
我正在尝试制作一个简单的链表,只有一个函数和两个指针。
#include <stdio.h>
#include <stdlib.h>
typedef struct leonor{
int x;
struct leonor * next;
}leo;
出于练习的目的,我总是在列表的末尾添加我创建的最后一个新节点。函数(add)如下:
void add(leo **ad)
{
int i;
leo *current, *new, **previous; /*Previous points on the pointer NEXT
*of an element*/
new=malloc(sizeof(*new));
for (i=0;i<3;i++)
{
printf("x : ");
scanf("%d",&new->x);
new->next=NULL;
previous = ad; /*'previous' receives adresse of head of list*/
current = *previous;
while(current != NULL) /*Look for last element of list*/
{
previous = &(current->next);
current = current->next;
}
new->next = *previous;
*previous = new;
}
}
其余代码:
void display_(leo *hl)
{
while (hl)
{
printf("%d -> ",hl->x);
hl=hl->next;
}
}
int main()
{
leo * head;
head = NULL;
add(&head);
display_(head);
return 0;
}
问题是在创建链表(此处为 3 个整数的列表)后,它总是只包含最后输入的数字。并且在显示结果时是相同数字的无限循环。非常感谢帮助。
【问题讨论】:
-
您需要处理的变量太多。特别是:
previous = ad;您不需要前面的变量,而是可以使用(并分配给)广告。
标签: c linked-list infinite-loop