forked from Wang-Jun-Chao/coding-interviews
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Test05.java
67 lines (61 loc) · 1.65 KB
/
Test05.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
56
57
58
59
60
61
62
63
64
65
66
67
import java.util.Stack;
/**
* Author: 王俊超
* Date: 2015-04-21
* Time: 21:36
* Declaration: All Rights Reserved !!!
*/
public class Test05 {
/**
* 结点对象
*/
public static class ListNode {
int val; // 结点的值
ListNode nxt; // 下一个结点
}
/**
* 输入个链表的头结点,从尾到头反过来打印出每个结点的值
* 使用栈的方式进行
*
* @param root 链表头结点
*/
public static void printListInverselyUsingIteration(ListNode root) {
Stack<ListNode> stack = new Stack<>();
while (root != null) {
stack.push(root);
root = root.nxt;
}
ListNode tmp;
while (!stack.isEmpty()) {
tmp = stack.pop();
System.out.print(tmp.val + " ");
}
}
/**
* 输入个链表的头结点,从尾到头反过来打印出每个结点的值
* 使用栈的方式进行
*
* @param root 链表头结点
*/
public static void printListInverselyUsingRecursion(ListNode root) {
if (root != null) {
printListInverselyUsingRecursion(root.nxt);
System.out.print(root.val + " ");
}
}
public static void main(String[] args) {
ListNode root = new ListNode();
root.val = 1;
root.nxt = new ListNode();
root.nxt.val = 2;
root.nxt.nxt = new ListNode();
root.nxt.nxt.val = 3;
root.nxt.nxt.nxt = new ListNode();
root.nxt.nxt.nxt.val = 4;
root.nxt.nxt.nxt.nxt = new ListNode();
root.nxt.nxt.nxt.nxt.val = 5;
printListInverselyUsingIteration(root);
System.out.println();
printListInverselyUsingRecursion(root);
}
}