06-从尾到头打印链表

    技术2022-07-10  99

    从尾到头打印链表

    ​ 题目描述

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

    ​ 示例

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

    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<>(); while(head != null) { stack.push(head.val); head = head.next; } int[] res = new int [stack.size()]; int index = 0; while(!stack.isEmpty()) { res[index++] = stack.pop(); } return res; } }

    时间复杂度:O(n),空间复杂度:O(n)

    Processed: 0.023, SQL: 9