我正在研究如何在开始时插入节点,我通过这段我无法理解的代码。
我没有得到打印功能。
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");
}
最佳答案
假设你的链表看起来像
a->b->c->d
|
|
head
所以现在我们使用一个临时变量
temp = head;
和
while(temp != NULL)
{
//Keep moving temp
printf("%d\n",temp->x);
temp = temp->next;
}
所以 head
永远不会移动,它只是移动到列表末尾的临时指针,当我们到达 temp = NULL
时,列表的末尾就到了
a->b->c->d
|
|
temp = head
temp = temp->next;
a->b->c->d
| |
| |
head temp
重复上述操作直到 temp = NULL
当最后一个节点内容被打印时为 TRUE,我们执行 temp = temp->next;
关于c - 在链表中插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28432270/