《剑指Offer(第2版)》-06-从尾到头打印链表

题目描述

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

示例 1:

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

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

题解

/**
 * 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<ListNode> stack = new Stack<ListNode>();
        ListNode temp = head;
	//循环遍历压栈
        while(temp!=null){
            stack.push(temp);
            temp = temp.next;
        }
        int size = stack.size();
//创建结果数组
        int[] res = new int[size];
//循环弹栈
        for(int i=0; i<size; i++){
            res[i] = stack.pop().val;
        }
        return res;
    }
}

复杂性分析

时间复杂度:O(n)。正向遍历一遍链表,然后从栈弹出全部节点,等于又反向遍历一遍链表。
空间复杂度:O(n)。额外使用一个栈存储链表中的每个节点。

发布了39 篇原创文章 · 获赞 15 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/sinat_35667067/article/details/104645046