我试图遍历单链表的程序,出现错误,似乎 do 和 while 循环没有正确应用,请检查
该程序位于下面我尝试使用 do while 和指针进行遍历的位置。
#include<stdio.h>
#include<stdlib.h>
int main()
{
char ch;
struct node
{
int info;
struct node *next;
};
typedef struct node node;
node *start, *ptr, *ne;
ptr=NULL;
int count=0;
do
{
ne=(node*) malloc(sizeof(node));
printf("\nEnter Data: ");
scanf("%d",&ne->info);
if(ptr!=NULL)
{
ptr->next=ne;
ptr=ptr->next;
}
else {
start=ne;
ptr=ne;
}
printf("\nDo you wish to continue?\n ");
scanf("%c",&ch);
}while(ch=='y'|| ch=='Y');
ptr->next=NULL;
printf("The linked list is: ");
ptr=start;
while(ptr!=NULL)
{
printf("\t%d",&ptr->info);
ptr=ptr->next;
count++;
}
printf("\nTotal number of elements: %d",count);
return(0);
}
最佳答案
改变
printf("\t%d",&ptr->info);
至
printf("\t%d",ptr->info);
另外,我不建议在 typedef struct node 节点中使用相同名称的“node”;
但这仍然不是问题。
编辑:
我还发现您的代码存在问题:
改变
printf("\nDo you wish to continue?\n ");
scanf("%c",&ch);
至
printf("\nDo you wish to continue?\n ");
getchar();
scanf("%c",&ch);
或者
您也可以将其更改为
printf("\nDo you wish to continue?\n ");
scanf(" %c",&ch); //add a space before %c
为什么这会导致错误?
在程序中,当您尝试使用“printf()”打印任何内容时,缓冲区中会留下一个空格,因此我们必须读取它并忽略它,否则 ch 将被分配空格。要读取空白并忽略,我们有两个选择,如上所述。尝试任何一种。
关于c++ - 错误(Id)返回 1 退出状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43306418/