寒夜憨憨 2021-06-21 11:34 采纳率: 71.4%
浏览 15
已采纳

单链表嵌套,但是在第二次调用嵌套链表打印时出现了null现象

以下为问题代码,在main里面我有注释过(重复函数调用)这个函数出现了嵌套链表为null的现象;

第一次打印时没有问题,当第二次调用打印时,在内部嵌套的那个链表为空;

如果把各个嵌套链表单独列出来单独打印或者多次调用打印函数都可以正常打印,就是全部嵌套时就不行.....

调试过各种,也怀疑过出现问题的能想到的问题,着时没思路了

本人小白

望高人指点迷津.......谢谢!

#include <stdio.h>
#include <stdlib.h>
#include "malloc.h"
struct stu
{
    int data;
    struct stu *next;//存放下一个结点的指针
};
struct cls
{
    int n;
    struct stu *cs;
    struct cls *next;//存放下一个结点的指针
};

struct stu *crs()
{
    printf("在stu crs里面\n");//验证
    struct stu *heads=NULL;
    struct stu *p,*news;
    while(1)
    {
        news=(struct stu *)malloc(sizeof(struct stu));
        printf("stu请输入 ");
        scanf("%d",&(news->data));
        if(news->data==0)
        {
            printf("stu over \n");//验证
            return heads;
        }

        if(heads==NULL)
        {
            heads=news;
        }
        else
        {

            while(p->next!=NULL)
            {
                p=p->next;
            }
            p->next=news;
        }
        p=news;
        news->next=NULL;
    }
}
//+++++++++++++++++++
//cls编组里面
struct cls *crc()
{
    printf("在clc crc里面\n");
    struct cls *headc=NULL;
    struct cls *p,*newc;
    while(1)
    {
        newc=(struct cls *)malloc(sizeof(struct cls));
        printf("cls请输入 ");
        scanf("%d",&(newc->n));
        newc->cs=crs();
        printf("cls->stu over \n");
        if(newc->n==0)
        {
            return headc;
        }
        if(headc==NULL)
        {
            headc=newc;
        }
        else
        {
            while(p->next!=NULL)
            {
                p=p->next;
            }
            p->next=newc;
        }
        p=newc;
        newc->next=NULL;
    }
}
//最终所有打印
void print(struct cls *allhead)
{
    struct cls *e=allhead;
    printf("所有第一次\n");
    while(e!=NULL)//遍历链表
    {
        printf("-------\n");
        printf("crc>%d\n",e->n);
        putchar('\n');
        while(e->cs!=NULL)
        {
            printf("%d ",e->cs->data);
            e->cs=e->cs->next;
        }
        e=e->next;
        putchar('\n');
    }
}

int main()
{   
    struct cls *head=NULL;
    head=crc();
    print(head);//打印
    printf("第二次打印\n");
    print(head);//重复调用打印
    return 0;
}

 

  • 写回答

1条回答 默认 最新

  • CSDN专家-link 2021-06-21 11:40
    关注

    e->cs=e->cs->next;

    你这修改了指针的内容了,你只能修改e

    e = e->cs;
    while(e!=NULL)
            {
                printf("%d ",e->data);
                e=e->next;
            }
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法