-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathSolution06.java
56 lines (50 loc) · 1.2 KB
/
Solution06.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
52
53
54
55
package sword_offer;
//page 58 从尾到头打印链表
import java.util.Stack;
//链表类
class ListNode{
ListNode next = null;
int value;
public void printOut() {
System.out.println(value);
ListNode tmp = next;
while (tmp != null) {
System.out.println(tmp.value);
tmp = tmp.next;
}
}
}
public class Solution06 {
//方法1:使用Stack栈的先push后pop
public static void printListReverse(ListNode listNode) {
Stack<ListNode> stack = new Stack<ListNode>();
while(listNode != null) {
stack.push(listNode);
listNode = listNode.next;
}
while(!stack.isEmpty()) {
System.out.println(stack.pop().value);
}
}
//方法2:使用递归的方式,相当于从内部往外部推
public static void printListReverse_rec(ListNode listNode) {
if(listNode != null) {
if (listNode.next != null)
printListReverse_rec(listNode.next);
System.out.println(listNode.value);
}
}
//测试
public static void main(String[] args) {
ListNode ln1 = new ListNode();
ListNode ln2 = new ListNode();
ListNode ln3 = new ListNode();
ln1.next = ln2;
ln2.next = ln3;
ln1.value = 1;
ln2.value = 2;
ln3.value = 3;
printListReverse_rec(ln1);
printListReverse(ln1);
}
}