Hugo Gao 2016-03-19 03:03 采纳率: 45.7%
浏览 1391
已采纳

为什么这个链表输出有问题?

#include
#include

typedef struct Node
{
int data;
struct Node *next;
}Node;
void append(Node *head)
{
int n;
Node *p,*news=NULL;
p=head;//保存首地址
while(1)
{
scanf("%d",&n);
if(n==-1)
{
break;
}
p->data=n;
news=(Node *)malloc(sizeof(Node));
news->next=NULL;
p->next=news;
p=news;
}
p=NULL;
}

void print(Node *head)
{
Node *p;
p=head;
while(p!=NULL)
{
printf("%d\t",p->data);
p=p->next;
}
}
int main()
{
Node *head=NULL;
head=(Node *)malloc(sizeof(Node));
append(head);
print(head);
return 0;
}

  • 写回答

2条回答 默认 最新

  • ai2018 2016-03-19 04:01
    关注

    1.问题出在append(head)中,你的链表最后会增加一个数值为随意值,但是不为空的节点。
    也就是说你输入1,2两个节点,其实链表最后是3个节点,第三个节点的值是未可知的。随意
    输入的结果最后是一个莫名其妙的数值。截图如下:
    图片说明
    2.正确的程序如下:

     #include <stdio.h>
    #include <stdlib.h>
    typedef struct Node {
        int data;
        struct Node *next;
    } Node;
    void append(Node *head) {
        int n;
        Node *p, *news = NULL;
        p = head; //保存首地址
        int index = 0; //head data inspector
        int count = 0;
        while (1) {
            scanf("%d", &n);
            if (n == -1) {
                break;
            }
    
            if (index == 0) {
                p->data = n;
                index++;
                continue;
            }
    
            news = (Node *) malloc(sizeof(Node));
            news->next = NULL;
            news->data = n;
            p->next = news;
            p = news;
            printf("the count is %d\n", count++);
        }
        p = NULL;
    }
    void print(Node *head) {
        Node *p;
        p = head;
        while (p != NULL) {
            printf("%d\t", p->data);
            p = p->next;
        }
    }
    int main() {
        Node *head = NULL;
        head = (Node *) malloc(sizeof(Node));
        append(head);
        print(head);
        system("pause");
        return 0;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 我这模型写的不对吗?为什么lingo解出来的下面影子价格这一溜少一个变量
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波