-
Notifications
You must be signed in to change notification settings - Fork 6
/
ReverseLinkedList.java
78 lines (74 loc) · 2.25 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
package io.ziheng.list.leetcode;
/**
* LeetCode 206. Reverse Linked List
* https://leetcode.com/problems/reverse-linked-list/
*/
public class ReverseLinkedList {
public ListNode reverseListRecursively(ListNode head, ListNode node) {
if (head == null) {
return node;
}
ListNode next = head.next;
head.next = node;
return reverseListRecursively(next, head);
}
public ListNode reverseListIteratively(ListNode head) {
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;
}
/**
* 反转单链表。
*
* 时间复杂度:O(n)
* 空间复杂度:O(1)
*/
public ListNode reverseList(ListNode head) {
return reverseListRecursively(head, null);
}
public ListNode buildLinkedList() {
ListNode head = new ListNode(-1);
ListNode currentNode = head;
for (int i = 0; i < 10; i++) {
ListNode newNode = new ListNode(i);
currentNode.next = newNode;
currentNode = currentNode.next;
}
return head;
}
public String listToString(ListNode head) {
if (head == null) {
return "null";
}
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append('[');
while (head != null) {
stringBuilder.append(head.val);
stringBuilder.append(", ");
head = head.next;
}
stringBuilder.append(']');
return stringBuilder.toString();
}
public static void main(String[] args) {
ReverseLinkedList reverseLinkedList = new ReverseLinkedList();
System.out.println(
reverseLinkedList.listToString(reverseLinkedList.buildLinkedList())
);
System.out.println(
reverseLinkedList.listToString(
reverseLinkedList.reverseList(
reverseLinkedList.buildLinkedList()
)
)
);
}
}
/* EOF */