本题要求实现一个函数,按输入数据的逆序建立一个链表。
函数接口定义:
struct ListNode *createlist();
函数createlist
利用scanf
从输入中获取一系列正整数,当读到−1时表示输入结束。按输入数据的逆序建立一个链表,并返回链表头指针。链表节点结构定义如下:
struct ListNode {
int data;
struct ListNode *next;
};
裁判测试程序样例:
#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(){
//按输入数据的逆序建立一个链表,头插法?
struct ListNode *p,*head;
head=(struct ListNode*)malloc(sizeof(struct ListNode));//分配内存
head->next=NULL;//创建头结点
int x=0;
scanf("%d",&x);//输入一个结点的值
while(x!=-1){
p=(struct ListNode*)malloc(sizeof(struct ListNode));//创建一个新结点
p->data=x;//下面代码使用头插法建立链表
p->next=head->next;
head->next=p;
scanf("%d",&x);
}
return head->next;//因为头结点没有赋值,如果返回头结点的话会多个0
}