单链表中的结点数据为什么输出两遍

杂家 2010-10-27 03:59:06
我想实现建立一个单链表,然后将其输出,但是为什么每个结点都输出2遍啊
#include<stdio.h>
struct node{
int data;
struct node * next;
};
struct node * createList(){
struct node *head,*p,*r;
int x;
char ch;
p=(struct node*)(malloc(sizeof(struct node)));
p->next=NULL;//生成头结点
head=p;
r=p;//建立单链表表尾指针
while(ch!='#')/为建立与否的标识符
{
scanf("%d",&x);
p=(struct node*)(malloc(sizeof(struct node)));
p->data=x;
p->next=NULL;//产生新结点
r->next=p;//连接新结点
r=p;
ch=getchar();
}
return head;
}
int main()
{
struct node * head,*p;
head=createList();
p=head->next;
while(p->next!=NULL)
{
printf("%d->",p->data);
p=p->next;
}
printf("%d\n",p->data);
system("pause");
return 1;
}
...全文
159 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
C4Fun 2010-10-27
  • 打赏
  • 举报
回复
逻辑问题,每次获取字符判断之前 Create了一个新节点 ,每当最后得到字符“#”的时候,局部变量X并没有改变依旧是前一个获取的数字。每次调用CreateList都会多创建一个最后次输入的冗余节点。
小楫轻舟 2010-10-27
  • 打赏
  • 举报
回复
原来这样,
那你要对输入格式进行更严格的限制,
+应该是字符,
但scanf()的格式是%d,
x还是上次的值
赵4老师 2010-10-27
  • 打赏
  • 举报
回复
单步调试和设断点调试是程序员必须掌握的技能之一。
杂家 2010-10-27
  • 打赏
  • 举报
回复
我的这个程序如果是0+96+3-9*8#
这种输入方式是没有问题的,
但是如果是
0
+
96
+
3
-
9
*
8
#
这种方式是不可以的
小楫轻舟 2010-10-27
  • 打赏
  • 举报
回复
int main()
{
struct node * head,*p;
head=createList();
p=head->next;
while(p->next!=NULL)
{
printf("%d->",p->data);
p=p->next;
}
//printf("%d\n",p->data); //就最后一个元素输出2次吧,因为这一句
system("pause");
return 1;
}


注:还要添加
#include <stdlib.h>
#include <malloc.h>
ch也没初始化
char ch = '\0';

69,369

社区成员

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

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