LC.P143[重排链表]

方法一:线性表+双指针

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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public void reorderList(ListNode head) {
List<ListNode> list = new ArrayList<>();
ListNode p = head;
while (p != null) {
list.add(p);
p = p.next;
}
int i = 0, j = list.size() - 1;
while (i < j) {
list.get(i).next = list.get(j);
++i;
if (i == j) break;
list.get(j).next = list.get(i);
--j;
}
list.get(i).next = null;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$

方法二:快慢指针+反转链表+合并链表

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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public void reorderList(ListNode head) {
ListNode fast = head, slow = head;
// 找到链表的中点
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
// 反转后半部分链表
ListNode pre = null, cur = slow.next;
slow.next = null;
while (cur != null) {
ListNode temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
// 合并链表,此时 cur 指向左半边第一个节点,pre 指向右半边第一个节点
cur = head;
while (pre != null) {
ListNode temp = pre.next;
pre.next = cur.next;
cur.next = pre;
cur = pre.next;
pre = temp;
}
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(1)$