输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2] 输出:[2,3,1]
使用ArrayList集合
class Solution { public int[] reversePrint(ListNode head) { ListNode temp = head; int length = 0; List<Integer> list = new ArrayList<>(); while(temp !=null){ length++; list.add(temp.val); temp = temp.next; } int[] res = new int[length]; for(int i=0;i<length;i++){ res[i] = list.get(length-i-1); } return res; } }运行结果 方法2: 符合栈的数据结构,先进出,用栈实现
public int[] reversePrint(ListNode head) { Stack<ListNode> stack = new Stack<ListNode>(); ListNode temp = head; while(null != temp){ stack.push(temp); temp = temp.next; } int length = stack.size(); int[] result = new int[length]; for(int i = 0;i<length;i++){ result[i] = stack.pop().val; } return result; }执行结果: 时间复杂度: O(n) n代表链表的长度 空间复杂度:O(n) n表示使用栈的长度(使用栈的长度取决于链表的长度,链表长度为n,所以栈使用的空间长度也是n)