本题要求实现一个函数,按输入数据的逆序建立一个链表。
函数接口定义:
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
代码:
struct ListNode* createlist()
{
struct ListNode* head = NULL;
struct ListNode* newNode;
int num;
scanf("%d", &num);
while (num != -1)
{
newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
newNode->data = num;
newNode->next = head;
head = newNode;
scanf("%d", &num);
}
return head;
}
完全详解(一步一步解析)
1.
struct ListNode *createlist();
表示该函数名为createlist
,返回类型为struct ListNode *
,即返回一个指向struct ListNode
结构体类型的指针。
2.
struct ListNode *head = NULL;
首先定义一个指向链表头的指针head
,初始化为NULL
,表示链表为空。
3.
int num;
scanf("%d", &num);
输入数字(判断第一个是不是-1和等会建立第一个节点)
4.
newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
在堆内存中为新节点分配空间。使用malloc
函数分配内存大小为sizeof(struct ListNode)
,并将返回的地址转换为struct ListNode *
类型,赋值给newNode
指针。
5.
newNode->data = num;
将读取到的整数num
赋值给新节点的data
成员,即将整数存储在新节点中。
6.
newNode->next = head;
将新节点的next
指针指向当前链表的头节点,实现将新节点插入到链表头部的操作。
逆序连接,想象一下
7.
head = newNode;
更新链表的头指针,使其指向新插入的节点,这样新节点就成为了链表的新头节点。