C语言链表问题:我输入1,2,3,4运行无限循环输出4,哪错了?
#include<stdio.h>#include<stdlib.h>intmain(){inti,x;typedefstructex{intnum;structex*n...
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i,x;
typedef struct ex
{
int num;
struct ex *next;
}ex;
ex *head,*tail;
head=(ex *)malloc(sizeof(ex));
if(head==NULL)
{
printf("error\n");
}
else
{
printf("success\n");
scanf("%d",&x);
head->num=x;
head->next=NULL;
tail=head;
}
for(i=0;i<3;i++)
{
tail=(ex *)malloc(sizeof(ex));
scanf("%d",&x);
head->next=tail;
tail->num=x;
}
while(tail!=NULL)
{
printf("%d\n",tail->num);
tail->next=tail;
}
} 展开
#include<stdlib.h>
int main()
{
int i,x;
typedef struct ex
{
int num;
struct ex *next;
}ex;
ex *head,*tail;
head=(ex *)malloc(sizeof(ex));
if(head==NULL)
{
printf("error\n");
}
else
{
printf("success\n");
scanf("%d",&x);
head->num=x;
head->next=NULL;
tail=head;
}
for(i=0;i<3;i++)
{
tail=(ex *)malloc(sizeof(ex));
scanf("%d",&x);
head->next=tail;
tail->num=x;
}
while(tail!=NULL)
{
printf("%d\n",tail->num);
tail->next=tail;
}
} 展开
展开全部
逻辑错误很多,你看我代码里的注释吧
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i,x;
typedef struct ex
{
int num;
struct ex *next;
}ex;
ex *head, *tail, *p; // 使用*p指向链表末尾
head = (ex*)malloc(sizeof(ex));
if(head==NULL) {
printf("error\n");
} else {
printf("success\n");
scanf("%d",&x);
head->num=x;
head->next=NULL;
// tail=head;
p=head;
}
for(i=0; i<3; i++) {
tail=(ex *)malloc(sizeof(ex));
scanf("%d",&x);
tail->num=x;
tail->next=NULL; // 新结点的指针域要设置为NULL,否则无法判断是否到了链表末尾
// head->next=tail;
p->next=tail; // 使用尾插法插入结点
p=p->next; // p始终指向链表末尾
}
tail = head; // 获取头结点
while(tail!=NULL) {
printf("%d\n",tail->num);
tail = tail->next;
// tail->next=tail;
}
return 0;
}
展开全部
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i,x;
typedef struct ex
{
int num;
struct ex *next;
}ex;
ex *current,*tail,*lead;
lead=(ex *)malloc(sizeof(ex));
if(lead==NULL)
{
printf("error\n");
}
else
{
printf("success\n请输入整型数字:");
scanf("%d",&x);
lead->num=x;
lead->next=NULL;
}
current = lead;
for(i=0;i<3;i++)
{
tail=(ex *)malloc(sizeof(ex));
printf("请输入整型数字:");
scanf("%d",&x);
tail->num=x;
tail->next = NULL;
current->next = tail;
current = tail;
}
current = lead;
while(current->next != NULL)
{
printf("%d\n",current->num);
current = current->next;
}
}
#include<stdlib.h>
int main()
{
int i,x;
typedef struct ex
{
int num;
struct ex *next;
}ex;
ex *current,*tail,*lead;
lead=(ex *)malloc(sizeof(ex));
if(lead==NULL)
{
printf("error\n");
}
else
{
printf("success\n请输入整型数字:");
scanf("%d",&x);
lead->num=x;
lead->next=NULL;
}
current = lead;
for(i=0;i<3;i++)
{
tail=(ex *)malloc(sizeof(ex));
printf("请输入整型数字:");
scanf("%d",&x);
tail->num=x;
tail->next = NULL;
current->next = tail;
current = tail;
}
current = lead;
while(current->next != NULL)
{
printf("%d\n",current->num);
current = current->next;
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
最后面那个while有问题,你把tail赋值给next了,但是tail并未改变,所以一直进入死循环
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询