-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode206.java
More file actions
88 lines (77 loc) · 2.33 KB
/
LeetCode206.java
File metadata and controls
88 lines (77 loc) · 2.33 KB
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
import util.ListNode;
import util.PrintUtil;
public class LeetCode206 {
public static void main(String[] args) {
ListNode head;
// 输入:head = [1,2,3,4,5]
// 输出:[5,4,3,2,1]
head = ListNode.buildLinkedList(new Integer[] { 1, 2, 3, 4, 5 });
System.out.println(head);
head = new Solution206_3().reverseList(head);
System.out.println(head);
PrintUtil.printDivider();
// 输入:head = [1,2]
// 输出:[2,1]
head = ListNode.buildLinkedList(new Integer[] { 1, 2 });
System.out.println(head);
head = new Solution206_3().reverseList(head);
System.out.println(head);
PrintUtil.printDivider();
// 输入:head = []
// 输出:[]
head = null;
System.out.println(head);
head = new Solution206_3().reverseList(head);
System.out.println(head);
PrintUtil.printDivider();
}
}
class Solution206_1 {
// NOTE: 递归版本
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newFirstNode = reverseList(head.next);
head.next.next = head;
head.next = null;
return newFirstNode;
}
}
class Solution206_2 {
// NOTE: 迭代版本
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode curNode = head;
ListNode res = null;
while (curNode != null) {
ListNode nextNode = curNode.next;
curNode.next = res;
res = curNode;
curNode = nextNode;
}
return res;
}
}
class Solution206_3 {
// NOTE: 迭代版本(更啰嗦)
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode curNode = head;
ListNode dummyNode = new ListNode();
dummyNode.next = head.next;
head.next = null;
while (dummyNode.next.next != null) {
ListNode tempNode = dummyNode.next.next;
dummyNode.next.next = curNode;
curNode = dummyNode.next;
dummyNode.next = tempNode;
}
dummyNode.next.next = curNode;
return dummyNode.next;
}
}