This question requires the realization of a function to establish a linked list in the reverse order of the input data. Function interface definition: 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;
}
/* Your code will be embedded here */
输入样例:1 2 3 4 5 6 7 -1
输出样例:7 6 5 4 3 2 1
My code
struct ListNode *createlist()
{
struct ListNode *p,*head; /*建立头结点和记录学生信息的指针p*/
do{
p=(struct ListNode*)malloc(sizeof(struct ListNode)); /*申请内存空间*/
scanf("%d",&p->data);
if(p->data!=-1){ /*判断输入的date 是否为-1*/
p->next=head; /*下一个指向头*/
head=p;
}
}while(p->data!=-1);
free(p);
return head;
}