面试题06. 从尾到头打印链表
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
解题
利用
Stack
栈先进后出的特征
import java.util.Arrays; import java.util.Stack; class Solution { static public int[] reversePrint(ListNode head) { Stack<Integer> stack = new Stack<>(); while (head!=null){ stack.push(head.val); head = head.next; } int ins[] = new int[stack.size()]; int i = 0; while (!stack.empty()){ ins[i]=stack.pop(); i++; } return ins; } public static void main(String[] args) { ListNode l1 = new ListNode(1); ListNode l2 = new ListNode(3); ListNode l3 = new ListNode(2); l1.next=l2; l2.next=l3; System.out.println(Arrays.toString(reversePrint(l1))); } }