逆序数据建立链表 (20分)

本题要求实现一个函数,按输入数据的逆序建立一个链表。
函数接口定义:
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=NULL,*head=NULL,*temp=NULL;//习惯定义三个(本题temp不用)
int x;
scanf("%d",&x);
while(x!=-1)
{
p=(struct ListNode *)malloc(sizeof(struct ListNode));
p->data=x;
p->next=head;//指向头结点
head=p;//头结点移动最新位置
scanf("%d",&x);
}
return head;
}
发布了36 篇原创文章 · 获赞 1 · 访问量 523

猜你喜欢

转载自blog.csdn.net/weixin_45821690/article/details/104525048