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