题目
本题要求实现一个函数,按输入数据的逆序建立一个链表。
函数接口定义:
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;
}
/* 你的代码将被嵌在这里 */
输入样例:
1 2 3 4 5 6 7 -1
输出样例:
7 6 5 4 3 2 1
AC代码
- 逆序数据建立链表其实就是头插法建立链表
struct ListNode *createlist(){
int tmp;
struct ListNode *p,*head=NULL;
scanf(" %d",&tmp);
while(tmp!=-1){
p=(struct ListNode*)(malloc(sizeof(struct ListNode)));
p->data=tmp;
if(head==NULL){ //表头为空则初始化链表
head=p;
head->next=NULL;
}
else{ //表头不为空,将新节点的后继指针指向头节点,头指针指向新节点
p->next=head;
head=p;
}
scanf(" %d",&tmp);
}
return head;
}