剑指 Offer 06. 从尾到头打印链表(C语言)
剑指 Offer 06. 从尾到头打印链表(C语言)
1. Title
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
详情:点击这里
2. Do it
2.1. version 0.1(success)
/*!
* @file 06reversePrint.c
* @date 2021-08
* @version 0.1
* @author forbit
* @brief 创建数组,遍历链表,从数组的末尾开始进行赋值。
* @details score 4ms 6.9-7.1MB。
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* reversePrint(struct ListNode* head, int* returnSize){
/*!
* @brief
* @param[in] head ListNode链表的头节点指针
* @param[in] returnSize 返回的数组的长度
* @return int类型的指针,返回数组。
*/
//! 入参判断,判断是否为空指针。
if(head == NULL){
* returnSize = 0;
return head;
}
//! 1. 获取链表的长度
int list_length = 1; //!< 初始化链表的长度为1
struct ListNode* head_copy; //!< 复制一个链表头节点的指针,用与计算链表长度
head_copy = head;
while( head_copy->next!=0 ){
list_length++;
head_copy = head_copy->next;
}
//! 2. 开辟空间
int space = list_length*4;
int *array = (int *)malloc(space);
if(array == NULL) exit(1); //! 开辟空间失败则退出
//! 3. 将链表中的值装载进去,倒过来赋值至数组
for(int i=list_length-1; i>=0; --i){
array[i] = head->val;
head = head->next;
}
* returnSize = list_length;
return array;
}

浙公网安备 33010602011771号