从尾到头打印链表
使用的linkedlist头插入,时间是40ms.
使用的栈结构,时间2ms.
public int[] reversePrint(ListNode head) {
if (head == null) return new int[0];
Stack<Integer> stack = new Stack<>();
while (head != null) {
stack.add(head.val);
head = head.next;
}
int size = stack.size();
int[] res = new int[size];
int i = 0;
while (!stack.empty()) {
res[i++] = stack.pop();
}
return res;
}