【发布时间】:2017-07-24 12:31:12
【问题描述】:
我有两个功能:
void display(struct node *start) {
struct node *ptr;
ptr = start;
while (ptr -> next != start) {
printf("\t %d", ptr -> data);
ptr = ptr -> next;
}
printf("\t %d", ptr -> data);
}
struct node *insert_beg(struct node *start) {
struct node *new_node;
new_node = (struct node *)malloc(sizeof(struct node));
printf("\n Enter data : ");
scanf("%d", &new_node -> data);
new_node -> next = start;
start = new_node;
return start;
}
使用insert_beg(start) 并尝试使用display(start) 显示此列表后,我有一个无限循环。
感谢您的支持。
【问题讨论】:
-
在函数
insert_beg中,变量start是一个本地 变量。一旦函数返回,您认为对它的更改会发生什么?我建议您搜索并阅读有关 emulating pass by reference in c。 -
@Someprogrammerdude 的评论是显而易见的(也是迄今为止最明智的),但您如何知道列表是循环的?它可能有一个起始尾部,例如数字 6。您的算法很容易受到攻击。
-
这是循环链表在哪里插入结束函数
-
请创建一个Minimal, Complete, and Verifiable Example 并告诉我们。也请花一些时间read about how to ask good questions。我还建议您阅读 Eric Lippert 的 How to debug small programs。
标签: c pointers struct linked-list