#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;
}
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;
}