-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathReverseLinkedList.java
131 lines (122 loc) · 3.07 KB
/
ReverseLinkedList.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package io.ziheng.codinginterviews;
import java.util.List;
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 面试题 24:反转链表
*
* 题目描述:
* 输入一个链表,反转链表后输出新链表的头节点。
*
* 知识点:["链表"]
*/
public class ReverseLinkedList {
/**
* 主函数 -> 测试用例
*
* @param args
* @return void
*/
public static void main(String[] args) {
ReverseLinkedList obj = new ReverseLinkedList();
ListNode head = buildList(
new int[]{1, 2, 3, 4, 5, }
);
System.out.println(
"Original Linked List: "
+ printList(head)
);
System.out.println(
"Reversed Linked List: "
+ printList(
// 迭代
obj.reverseLinkedListIteratively(head)
// 递归
// obj.reverseLinkedListRecursively(head, null)
)
);
}
/**
* 迭代
*
* @param head
* @return ListNode
*/
public ListNode reverseLinkedListIteratively(ListNode head) {
// 处理异常情况
if (head == null) {
return null;
}
ListNode previousNode = null;
ListNode currentNode = head;
ListNode nextNode = head.next;
while (currentNode != null) {
nextNode = currentNode.next;
currentNode.next = previousNode;
previousNode = currentNode;
currentNode = nextNode;
}
return previousNode;
}
/**
* 递归 {@code reverseLinkedListRecursively(head, null)}
*
* @param head
* @param node
* @return ListNode
*/
public ListNode reverseLinkedListRecursively(ListNode head, ListNode node) {
if (head == null) {
return node;
}
ListNode next = head.next;
head.next = node;
return reverseLinkedListRecursively(next, head);
}
/**
* 单向链表转列表
*
* @param head
* @return ListNode
*/
public static List<Integer> printList(ListNode head) {
List<Integer> resultList = new LinkedList<>();
ListNode currentNode = head;
while (currentNode != null) {
resultList.add(currentNode.val);
currentNode = currentNode.next;
}
return resultList;
}
/**
* 快速构建单向链表
*
* @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;
}
}
/* EOF */