C 在循环链表的开头插入
我在循环链表的开头插入,但输出打印了一些垃圾值C 在循环链表的开头插入,c,data-structures,linked-list,circular-list,C,Data Structures,Linked List,Circular List,我在循环链表的开头插入,但输出打印了一些垃圾值 typedef struct Node { int info; struct Node *next; }node; node *head; void insert(int x) //x will the value given by the user { node *ptr,*ptr1; //ptr1 for pointing the last node
typedef struct Node
{
int info;
struct Node *next;
}node;
node *head;
void insert(int x) //x will the value given by the user
{
node *ptr,*ptr1;
//ptr1 for pointing the last node again to first node
ptr=(node*)malloc(sizeof(node));
ptr->info=x;
if(head==NULL)
{
ptr->next=head;
head=ptr;
ptr1=ptr;
}
else
{
ptr->next=head;
head=ptr;
}
head->next=ptr1;
}
void show()
{
node *temp=head;
while(temp!=NULL)
{
printf("%d",temp->info);
temp=temp->next;
}
printf("\n");
}
您有两个问题,一个导致无限列表,另一个导致 在列表中插入第一个节点时得到的无限列表,原因如下:
head->next=ptr1;
到那时,head
和ptr
和ptr1
都指向同一个节点,因此通过上面的赋值,您可以说列表中的下一个节点是。。。本身
在另一种情况下,当列表不为空时,会出现未定义的行为,其原因与上面的赋值相同:
head->next=ptr1;
在这里,变量ptr1尚未初始化,未初始化的局部(非静态)变量具有不确定的值,使用这些变量进行初始化会导致未定义的行为
实际上,未定义的行为不会在赋值时发生,但会在下次尝试取消引用head->next
时发生,因为该指针无效
这两个问题的简单解决方案是什么?不要做最后的作业 您不会在else{}分支中将任何内容分配给ptr1,但稍后将ptr1值存储为head->next。由于ptr1未初始化,所以打印列表时会收到垃圾。但接下来我将如何实现循环列表。@初学者将最后一个节点
next
指针指向head
。