辉哥哥哟 2022-03-23 23:13 采纳率: 100%
浏览 33
已结题

单链表输出问题c++

问题遇到的现象和发生背景

带头结点的单链表输出时为什么没有指向所应指向的指针也能输出正确结果,真的很懵逼(调试的时候发现的)

问题相关代码,请勿粘贴截图
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
typedef int datatype;
typedef struct node
{
    datatype data;
    struct node *next;
} node;
typedef node *linklist;
node *init()
{
    node *head;
    head = (node *)malloc(sizeof(node));
    head->next = NULL;
    return head;
}

void output1(node *head)
{
    node *s;
    int i = 0;
    if (!s)
    {
        cout << "空的";
        return;
    }
    cout << "链表为:";
    while (s)
    {
        cout << s->data << ' ';
        i++;
        if (i % 10 == 0)
            cout << endl;
        s = s->next;
    }
    cout << endl;
}

void createbystack1(node *head)
{
    node *p = head;
    node *s;
    datatype x;
    cout << "请输入若干数据,以0为结束符" << endl;
    cin >> x;
    while (x)
    {
        s = new node;
        s->data = x;
        if (head->next == NULL)
        {
            head->next = s;
            s->next = NULL;
            p = s;
        }
        else
        {
            head->next = s;
            s->next = p;
            p = s;
        }
        cin >> x;
    }
}

int main()
{
    node *head;
    head = init();
    createbystack1(head);
    output1(head);
    system("pause");
    return 0;
}

运行结果及报错内容

请输入若干数据,以0为结束符
1 2 3 4 5 6 0
链表为:6 5 4 3 2 1
请按任意键继续. . .
真的不懂为什么能运行成功,希望得到您的解惑,,谢谢

我的解答思路和尝试过的方法
我想要达到的结果
  • 写回答

2条回答 默认 最新

  • 关注

    output1函数里,s没有赋值也没有初始化就直接用了,s不初始化的时候,给的值是不一定的,有的编译器会把它赋值为0,有的则是一个随机值。
    需要让s = head->next;

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 4月18日
  • 已采纳回答 4月10日
  • 创建了问题 3月23日

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)