【leetcode C语言实现】剑指 Offer 06. 从尾到头打印链表

题目描述

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

示例 1:

输入:head = [1,3,2]
输出:[2,3,1]

限制:
0 <= 链表长度 <= 10000

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof

解题思路

由于遍历链表只能从头到尾,先遍历的后打印,这是典型的“先进后出”,即栈结构。
此处采用数组存储依次遍历到的数据,由于链表大小未知,而链表长度限制在0-10000之间,因此声明一个含有10000个元素的数组,从后往前依次存储,最后返回实际存储数据的部分。

代码

/**
 * 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){

    int len = 10000;
    int num = 0;
    struct ListNode * pnode = head;
    int * list = (int *)malloc(len * sizeof(int));
    int i;

    if(NULL == pnode)
    {
        *returnSize = 0;
        return NULL;
    }

    while(pnode)
    {
        list[--len] = pnode->val;
        num++;
        pnode = pnode->next;
    }

    *returnSize = num;
    return &list[len];
}

执行结果

时间复杂度O(n)
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/sunshine_hanxx/article/details/106952825