-
Notifications
You must be signed in to change notification settings - Fork 148
/
PrintListReversing5.java
51 lines (44 loc) · 1.2 KB
/
PrintListReversing5.java
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package com.so;
import java.util.ArrayList;
import java.util.Stack;
import com.so.Common.ListNode;
/**
* 第5题 从尾到头打印链表
* 输入一个链表,从尾到头打印链表每个节点的值
*
* @author qgl
* @date 2017/08/08
*/
public class PrintListReversing5 {
/**
* 解法一:利用栈输出
* @param headNode
*/
public static ArrayList<Integer> printListReverse1(ListNode headNode) {
ArrayList<Integer> list = new ArrayList<>();
Stack<ListNode> stack = new Stack<>();
while (headNode != null) {
stack.push(headNode);
headNode = headNode.next;
}
while (!stack.isEmpty()) {
list.add(stack.pop().val);
}
return list;
}
/**
* 解法二:递归(其实底层还是栈)
* @param headNode
* @return
*/
public static ArrayList<Integer> printListReverse2(ListNode headNode) {
ArrayList<Integer> list = new ArrayList<Integer>();
if (headNode != null) {
if (headNode.next != null) {
list = printListReverse2(headNode.next);
}
list.add(headNode.val);
}
return list;
}
}