-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathPrintList.java
67 lines (61 loc) · 1.71 KB
/
PrintList.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
package org.offer.case05;
import org.offer.utils.node.Node;
import org.offer.utils.Stack;
/**
* 面试题 5:从尾到头打印链表
* Created by tanc on 2017/3/20.
*/
public class PrintList {
/**
* 顺序打印链表
*
* @param head 链表的头节点,这里头结点是单独的一个节点,与链表内容无关
*/
public static <T extends Comparable<? super T>> void order(Node<T> head) {
Node<T> temp = head;
while (temp.next != null) {
temp = temp.next;
System.out.print(temp.data);
System.out.print(" ");
}
}
/**
* 使用递归实现从尾到头打印链表
*
* @param head 链表的头节点
*/
public static <T extends Comparable<? super T>> void tailByRecursion(Node<T> head) {
if (null == head || null == head.next) {
return;
}
print(head.next);
}
private static <T extends Comparable<? super T>> void print(Node<T> head) {
if (null == head) {
return;
}
print(head.next);
System.out.print(head.data);
System.out.print(" ");
}
/**
* 使用栈实现从尾到头打印链表
*
* @param head 链表的头节点
*/
public static <T extends Comparable<? super T>> void tailByStack(Node<T> head) {
if (null == head || null == head.next) {
return;
}
Node<T> temp = head;
Stack<T> stack = new Stack<>();
while (temp.next != null) {
temp = temp.next;
stack.push(temp.data);
}
while (!stack.isEmpty()) {
System.out.print(stack.pop());
System.out.print(" ");
}
}
}