shilly12138 2020-03-31 16:36 采纳率: 0%
浏览 902

逆序数据建立链表--按输入数据的逆序建立一个链表

要求实现一个函数,按输入数据的逆序建立一个链表

函数createlist利用scanf从输入中获取一系列正整数,当读到−1时表示输入结束。按输入数据的逆序建立一个链表,并返回链表头指针。
题目给出的代码:

#include <stdio.h>
#include <stdlib.h>

struct ListNode {
    int data;
    struct ListNode *next;
};

struct ListNode *createlist();

int main()
{
    struct ListNode *p, *head = NULL;

    head = createlist();
    for ( p = head; p != NULL; p = p->next )
        printf("%d ", p->data);
    printf("\n");

    return 0;
}

正确答案代码:

/* 你的代码将被嵌在这里 */
struct ListNode *createlist(){
    int num;
    struct ListNode *p=NULL,*head=NULL;
    scanf("%d",&num);
    while (num!=-1) {
        p=(struct ListNode*)malloc(sizeof(struct ListNode));//注意这里!!!
        p->data=num;
        p->next=head;
        head=p;
        scanf("%d",&num);
    }
    return head;
}

输出结果:

6 5 -1
5 6 
Program ended with exit code: 0

错误代码(将上述标注的代码行换了个位置):

struct ListNode *createlist(){
    int num;
    struct ListNode *p=NULL,*head=NULL;
    scanf("%d",&num);
      p=(struct ListNode*)malloc(sizeof(struct ListNode));//换到while循环外面!!
    while (num!=-1) {
        p->data=num;
        p->next=head;
        head=p;
        scanf("%d",&num);
    }
    return head;
}

输出结果:

6 5 -1
5 5 5 5 5 5 5 5 5 5 5 ……

为什么会这样呢?

  • 写回答

1条回答 默认 最新

  • CSDN-Ada助手 CSDN-AI 官方账号 2022-09-09 15:30
    关注
    不知道你这个问题是否已经解决, 如果还没有解决的话:

    如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 以帮助更多的人 ^-^
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog