-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathPrintLinkedListFromTailToHead.java
92 lines (89 loc) · 2.31 KB
/
PrintLinkedListFromTailToHead.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package io.ziheng.codinginterviews;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.LinkedList;
/**
* 单链表
*/
class ListNode {
public int val;
public ListNode next;
public ListNode(int val) {
this.val = val;
this.next = null;
}
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
/**
* 剑指 Offer 面试题 05:从尾到头打印链表
*
* 题目描述:
* 输入一个单向链表,按链表从尾到头的顺序返回一个 ArrayList 。
*
* 知识点:["链表"]
*/
public class PrintLinkedListFromTailToHead {
/**
* 主函数 -> 测试用例
*
* @param args
* @return void
*/
public static void main(String[] args) {
PrintLinkedListFromTailToHead obj = new PrintLinkedListFromTailToHead();
int[] arr = new int[]{1, 2, 3, 4, 5, };
ListNode head = buildList(arr);
System.out.println(
"Original LinkedList: "
+ Arrays.toString(arr)
);
System.out.println(
"Reversed LinkedList: "
+ obj.printListFromTailToHead(head).toString()
);
}
/**
* 快速构建单向链表
*
* @param arr
* @return ListNode
*/
public static ListNode buildList(int[] arr) {
ListNode dummyhead = new ListNode(0);
ListNode currentNode = dummyhead;
for (int n : arr) {
ListNode node = new ListNode(n);
currentNode.next = node;
currentNode = currentNode.next;
}
return dummyhead.next;
}
/**
* 剑指 Offer 面试题 05:从尾到头打印链表
*
* 时间复杂度:O(n)
* 空间复杂度:O(n)
*
* @param head
* @return {@code List<Integer>}
*/
public List<Integer> printListFromTailToHead(ListNode head) {
List<Integer> resultList = new ArrayList<>();
Deque<Integer> aStack = new LinkedList<>();
ListNode currentNode = head;
while (currentNode != null) {
aStack.push(currentNode.val);
currentNode = currentNode.next;
}
while (!aStack.isEmpty()) {
resultList.add(aStack.pop());
}
return resultList;
}
}
/* EOF */