要求实现一个函数,按输入数据的逆序建立一个链表
函数createlist利用scanf从输入中获取一系列正整数,当读到−1时表示输入结束。按输入数据的逆序建立一个链表,并返回链表头指针。
题目给出的代码:
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int data;
struct ListNode *next;
};
struct ListNode *createlist();
int main()
{
struct ListNode *p, *head = NULL;
head = createlist();
for ( p = head; p != NULL; p = p->next )
printf("%d ", p->data);
printf("\n");
return 0;
}
正确答案代码:
/* 你的代码将被嵌在这里 */
struct ListNode *createlist(){
int num;
struct ListNode *p=NULL,*head=NULL;
scanf("%d",&num);
while (num!=-1) {
p=(struct ListNode*)malloc(sizeof(struct ListNode));//注意这里!!!
p->data=num;
p->next=head;
head=p;
scanf("%d",&num);
}
return head;
}
输出结果:
6 5 -1
5 6
Program ended with exit code: 0
错误代码(将上述标注的代码行换了个位置):
struct ListNode *createlist(){
int num;
struct ListNode *p=NULL,*head=NULL;
scanf("%d",&num);
p=(struct ListNode*)malloc(sizeof(struct ListNode));//换到while循环外面!!
while (num!=-1) {
p->data=num;
p->next=head;
head=p;
scanf("%d",&num);
}
return head;
}
输出结果:
6 5 -1
5 5 5 5 5 5 5 5 5 5 5 ……
为什么会这样呢?