剑指 Offer 06. 从尾到头打印链表

转载自Leet Code《剑指Offer》

题目描述

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

示例

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

提示:

  • 0 <= 链表长度 <= 10000

我的思路

由于链表只能从头到尾遍历的特性,利用栈来实现对其从尾到头的打印。

首先,如果链表头指向NULL的话,返回一个长度为0的数组。 否则,为其准备一个栈stack,将遍历的每一个链表值入栈。 最后准备一个和栈大小相同的数组,将栈中元素逐一弹出并放入数组,将数组返回。


我的代码

{.line-numbers}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class MySolutionOffer06 {
public int[] reversePrint(ListNode head) {
if (head==null)
{
int []ans = new int[0];
return ans;
}

Stack<Integer> stack = new Stack();
ListNode p = head;
while(p!=null)
{
stack.push(p.val);
p = p.next;
}

int []ans = new int[stack.size()];
for(int i=0; i<ans.length; i++)
ans[i]=stack.pop();

return ans;
}
}