【发布时间】:2017-09-04 12:12:20
【问题描述】:
我试图遍历单链表的程序,出现错误,似乎 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);
}
【问题讨论】:
-
如果链接器返回错误(您没有复制到帖子中),您的程序将无法运行。所以问题不在于没有“应用”循环。
-
在询问构建错误时,总是在问题正文中包含 complete 错误输出。完整、完整,包括可能的信息说明,无需编辑,作为(复制粘贴)文本。
标签: c++ c data-structures linked-list