单链表的建立

Jackzhawy 2011-09-07 12:02:59
#include<stdio.h>
#include<stdlib.h>
#define NULL 0
struct node{
int data;
struct node *next;
};
struct node *build()
{ int x;
struct node *head,*tail,*p;
head=tail=NULL;
printf("please input x\n");
scanf("%d",&x);
while(x!=0)
{ p=(struct node*)malloc(sizeof(struct node));
p->data=x;
p->next=NULL;
if(head==NULL)
head=tail=p;
else
{ tail->next=p;
tail=p;
}
scanf("%d",&x);

return head;
}
}
void main()
{ struct node *q;
q=build();
printf("%d",q->data);
q=q->next;
getch();
}
结果:输入 1 2 3 4 5 0; 显示只能是1.为什么只能显示第一个数啊.请高手们指点指点,谢谢!
...全文
85 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
lcunjc 2011-09-07
  • 打赏
  • 举报
回复
1.build里面输入了一次就返回了,return head;应该在while循环外面
2.输出明显也只输出了一次
正确代码

#include<stdio.h>
#include<stdlib.h>
#define NULL 0
struct node
{
int data;
struct node *next;
};
struct node *build()
{
int x;
struct node *head,*tail,*p;
head=tail=NULL;
printf("please input x\n");
scanf("%d",&x);
while(x!=0)
{
p=(struct node*)malloc(sizeof(struct node));
p->data=x;
p->next=NULL;
if(head==NULL)
head=tail=p;
else
{
tail->next=p;
tail=p;
}
scanf("%d",&x);


}
return head;
}
void main()
{
struct node *q;
q=build();
while(q != NULL)
{
printf("%d ",q->data);
q=q->next;
}
getchar();
}
Jackzhawy 2011-09-07
  • 打赏
  • 举报
回复
亲们:谢了,刚搞出来了!
huhaifengasd 2011-09-07
  • 打赏
  • 举报
回复
同上面 加while循环
Jackzhawy 2011-09-07
  • 打赏
  • 举报
回复
怎么结果还没出来就一闪而过了>
暮雨晨舟 2011-09-07
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 lcunjc 的回复:]
1.build里面输入了一次就返回了,return head;应该在while循环外面
2.输出明显也只输出了一次
正确代码

C/C++ code

#include<stdio.h>
#include<stdlib.h>
#define NULL 0
struct node
{
int data;
struct node *next;
};
stru……
[/Quote]
++

69,382

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧