C语言链表问题:我输入1,2,3,4运行无限循环输出4,哪错了?

2025-04-09 21:12:27
推荐回答(3个)
回答1:

逻辑错误很多,你看我代码里的注释吧

#include
#include
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;
}

回答2:

#include
#include
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;
}
}

回答3:

最后面那个while有问题,你把tail赋值给next了,但是tail并未改变,所以一直进入死循环