寒夜憨憨 2021-06-21 11:34 采纳率: 20%
浏览 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;
            }
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办