gpt4 book ai didi

c - 在打印链接列表的状态时程序进入无限循环

转载 作者:太空宇宙 更新时间:2023-11-04 00:02:04 25 4
gpt4 key购买 nike

我制作了一个简单的链表程序,当我打印链表中的值时,它进入了无限循环。我特此附上代码。我制作了 temp1 用于遍历目的。'a' 用于存储头节点的地址。'temp' 用于创建新节点。

// Creating a menu deriv en program of single link list
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node{
int data;
struct node *next;
};
void main()
{
struct node *a;
char ch;
struct node *temp;
struct node *temp1;
a=NULL;
clrscr();
do
{
if(a==NULL)
{
temp=(struct node*)malloc(sizeof(struct node));
printf("Enter Data");
scanf("%d",&temp->data);
temp->next=NULL;
a=temp;
}
else
{
temp=(struct node*)malloc(sizeof(struct node));
printf("Enter data element");
scanf("%d",&temp->data);
temp1=a;
while(temp1->next!=NULL)
{
temp1=temp1->next;
}
temp1->next=temp;
}
printf("Do You Wish to continue");
ch=getch();
}
while(ch=='Y'||ch=='y');
printf("Status of the link list");
temp1=a;
while(temp1!=NULL)
{
printf("%d ",temp1->data);
temp1->next=temp1;
}
getch();
}

请帮忙!!!

最佳答案

在您的代码中,您犯了两个错误。

1st Mistake

进入 else block 后,您没有将新创建节点的 next 指针设置为 NULL。所以您在 else 中的代码应该是像这样……

else
{
temp=(struct node*)malloc(sizeof(struct node));
temp->next=NULL;
printf("Enter data element");
scanf("%d",&temp->data);
temp1=a;
while(temp1->next!=NULL)
{
temp1=temp1->next;
}
temp1->next=temp;
}

2nd Mistake

在尝试打印链表时,在while循环中遍历指针的推进是错误的。所以你打印链表的代码应该是这样的......

while(temp1!=NULL)
{
printf("%d ",temp1->data);
temp1=temp1->next;
}

尝试通过将情况画在纸上来形象化情况,然后您会更加清楚。

关于c - 在打印链接列表的状态时程序进入无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39038509/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com