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 vhdl+MODELSIM
  • ¥20 simulink中怎么使用solve函数?
  • ¥30 dspbuilder中使用signalcompiler时报错Error during compilation: Fitter failed,求解决办法
  • ¥15 gwas 分析-数据质控之过滤稀有突变中出现的问题
  • ¥15 没有注册类 (异常来自 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
  • ¥15 知识蒸馏实战博客问题
  • ¥15 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题