2016-03-19 03:03

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

#include
#include

typedef struct Node
{
int data;
struct Node *next;
}Node;
{
int n;
Node *p,*news=NULL;
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;
}

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

• 点赞
• 写回答
• 关注问题
• 收藏
• 邀请回答

#### 2条回答默认 最新

• ai2018 2016-03-19 04:01
已采纳

也就是说你输入1,2两个节点，其实链表最后是3个节点，第三个节点的值是未可知的。随意
输入的结果最后是一个莫名其妙的数值。截图如下：

2.正确的程序如下：

`````` #include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
int n;
Node *p, *news = NULL;
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;
}
Node *p;
while (p != NULL) {
printf("%d\t", p->data);
p = p->next;
}
}
int main() {