【发布时间】:2015-02-10 12:57:22
【问题描述】:
我正在研究如何在开头插入节点,我通过了这段我无法理解的代码。
我没有得到打印功能。
typedef struct node
{
int data;
struct node *next;
} Node;
Node *head;
void insert(int x)
{
Node *temp=(Node*)malloc(sizeof(Node));
temp->data=x;
temp->next=head;
head=temp;
}
void print()
{
Node *temp=head;
printf("List is:");
while(temp!=NULL) //Unable to understand this statement as how will the loop terminate?
{
printf("%d ",temp->data);
temp=temp->next;
}
printf("\n");
}
【问题讨论】:
-
temp=temp->next;行更改 temp,在列表末尾的 next 指向 NULL,因此条件temp!=NULL不再为真 -
请正确缩进您的代码。
-
在调试器中运行,逐行执行代码,看看会发生什么。
-
所以“下一个”最后会自动初始化为 NULL,因为我没有在任何地方将它初始化为 NULL。
-
没有自动魔法。您找到的代码假定列表为 NULL 终止
标签: c data-structures linked-list