【剑指 Offer II】 06. 从尾到头打印链表

138 阅读2分钟

leetcode链接:剑指 Offer 06. 从尾到头打印链表

题目描述

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

示例:

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

限制:

0 <= 链表长度 <= 10000

解题思路

方法一:栈

栈的特点是后进先出,即最后压入栈的元素最先弹出,遍历链表,将所有节点值push到栈中,再pop到一个数组中,时间复杂度:O(n) 空间复杂度:O(n)

方法二:反转链表

要实现反转链表,有很多办法比如:迭代法、栈辅助法、新建链表法和递归法等。
参考链接:反转链表-四种方法
这里主要讲一下用递归的思想来实现反转,先走至链表末端,回溯时依次将节点值加入列表 ,这样就可以实现链表值的倒序输出。
递推阶段: 每次传入 head.next ,以 head == null(即走过链表尾部节点)为递归终止条件,此时直接返回。
回溯阶段: 层层回溯时,将当前节点值加入列表 temp
最终,将列表 temp 转化为数组 output ,并返回。
时间复杂度:O(n) 空间复杂度:O(n)

方法三:遍历链表,反向放入数组中

先统计链表节点个数count,new一个大小为count的数组,遍历链表,从数组的最后一个位置开始往前放置节点的值,时间复杂度:O(n) 空间复杂度:O(1)

代码实现

方法一:栈

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public int[] reversePrint(ListNode head) {
        Stack<Integer> stack = new Stack<Integer>();
        ListNode temp = head;
        while(temp != null){
            stack.push(temp.val);
            temp = temp.next;
        }
        int size = stack.size();
        int[] output = new int[size];
        for(int i = 0; i < size; i++){
            output[i] = stack.pop();
        }
        return output;
    }
}

image.png

方法二:反转链表(递归法)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    ArrayList<Integer> temp = new ArrayList<Integer>();
    public int[] reversePrint(ListNode head) {
        recur(head);
        int[] output = new int[temp.size()];
        for(int i = 0; i < output.length; i++){
            output[i] = temp.get(i);
        }
        return output;
    }
    void recur(ListNode head){
        //递推与回溯
        if(head == null){
            return ;
        }
        recur(head.next);
        temp.add(head.val);
    }
}

image.png

方法三:遍历链表,反向放入数组中

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public int[] reversePrint(ListNode head) {
        //后来发现,无需先前判断是否为空
        //if(head == null){
        //    return new int[0];
        //}
        // 统计链表节点个数,方便创建数组
        int count = 0;
        ListNode temp = head;
        while(temp != null ){
            count ++;
            temp = temp.next;
        }
        int[] output = new int[count];
        for(int i = output.length - 1; i >= 0; i--){// 从由往左填充数组
            output[i] = head.val;
            head = head.next;
        }
        return output;
    }
}

image.png

我的思考

分析方法三的空间复杂度时,一开始认为是O(n),但是实际上是O(1),这让我疑惑了很久,因为我觉得自己new的数组大小是会随着链表大小变化而变化,所以觉得应该是O(n)呀,后来是 帅地 大佬给我答疑解惑: image.png 我豁然开朗😂😂😂,作为算法门徒,还是有很多需要学习的地方呀哈哈。
通过这道题,使用不同的方法,巩固了链表递归等基础知识,收获还是不少。 这道题其实是反转链表的变体,题目要求用数组返回,所以有了方法三这一“最优解”吧,所以先仔细读题,看清题目要求,这是解题十分重要的第一步。


此文章是我的第四篇刷题总结,比较基础,希望能和大家一起学习,我也会努力更新《剑指offer》其他题目,加油!