简单的链表不知道错在哪里

hai00jiao 2009-12-22 09:52:50
就是实现动态输入一些数,然后再输出来,每次只能输出链表最后一个数据!
#include<stdio.h>
#include<malloc.h>
typedef struct node
{
int data;
node* next;
}node;
node*create()
{
int i=0;
node *p,*q,*head;
int x=0;
head=(node*)malloc(sizeof(node));

while(1)
{
printf("Please input a data!\n");
scanf("%d",&x);
if(x==0) break;

p=(node*)malloc(sizeof(node));
p->data=x;
if(++i=1)
{
head->next=p;
}
else
{
q->next=p;
}
q=p;
}
q->next=NULL;
return head;
}
void print(node *head)
{
node *p;
int index=0;
if(head->next==NULL)
{
printf("empty");
return;
}
p=head->next;
while(p!=NULL)
{
printf("the %dth node is %d\n",++index,p->data);
p=p->next;
}
}
void main()
{
node *head=create();
print(head);
}

...全文
81 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
hai00jiao 2009-12-22
  • 打赏
  • 举报
回复
非常感谢二楼
mmilmf 2009-12-22
  • 打赏
  • 举报
回复
问题已标记,不要使用其他变量来控制创建链表,如你使用int i = 0;
根据链表自身的特性就可以啦,既然创建的链表带有表头,那么初始创建
链表的时候head->next必是NULL,由此来创建链表......
mmilmf 2009-12-22
  • 打赏
  • 举报
回复

node * create()
{
int i=0;
node *p,*q,*head;
int x=0;
head=(node*)malloc(sizeof(node));
head-> next = NULL ; //mark
while(1)
{
printf("Please input a data!\n");
scanf("%d",&x);
if(x==0) break;

p=(node*)malloc(sizeof(node));
p->data=x;
//if(++i=1)
if(head->next == NULL ) //mark
{
head->next=p;
}
else
{
q->next=p;
}
q=p;
}
q->next=NULL;
return head;
}

结果
Please input a data!
2
Please input a data!
3
Please input a data!
6
Please input a data!
1
Please input a data!
0
the 1th node is 2
the 2th node is 3
the 3th node is 6
the 4th node is 1
Press any key to continue
Eleven 2009-12-22
  • 打赏
  • 举报
回复
if(++i=1)
{
head->next=p;
}

条件永远为TRUE

19,468

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 图形处理/算法
社区管理员
  • 图形处理/算法社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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