剑指offer06 从尾到头打印链表

题目

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

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

 限制: 
 0 <= 链表长度 <= 10000 
 Related Topics 栈 递归 链表 双指针 

方法

  • 时间复杂度:O(n)
  • 空间复杂度:O(n)
class Solution {
    public int[] reversePrint(ListNode head) {
        Stack<Integer> stack = new Stack<>();
        ListNode node = head;
        while(node!=null){
            stack.push(node.val);
            node = node.next;
        }
        int length = stack.size();
        int[] result = new int[length];
        for(int i=0;i<length;i++){
            result[i] = stack.pop();
        }
        return result;
    }
}

深度优先遍历

  • 时间复杂度:O(n)
  • 空间复杂度:O(n)
class Solution {
    public int[] reversePrint(ListNode head) {
        List<Integer> arr = new ArrayList<>();
        dfs(head,arr);
        int[] ans = new int[arr.size()];
        for(int i=0;i<arr.size();i++){
            ans[i] = arr.get(i);
        }
        return ans;
    }
    private void dfs(ListNode node,List<Integer> arr){
        if(node==null){
            return;
        }
        dfs(node.next,arr);
        arr.add(node.val);
    }
}
posted @ 2021-08-10 12:23  你也要来一颗长颈鹿吗  阅读(25)  评论(0)    收藏  举报