143.重排链表

题目描述

QQ截图20201020145804

题解

快慢指针 + 反转链表

先通过快慢指针的方法找出链表的中间节点, 以此为边界把后半段链表反转, 然后交错插入前半段链表中

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
public class lc143 {
public void reorderList(ListNode head) {
if (head == null || head.next == null) {
return;
}
ListNode slow = head;
ListNode fast = head.next;

while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}

ListNode head2 = reverse(slow.next);
slow.next = null;

ListNode pre = head;
ListNode cur;
ListNode cur2;

while (head2 != null) {
cur = pre.next;
cur2 = head2.next;

head2.next = pre.next;
pre.next = head2;

pre = cur;
head2 = cur2;
}

System.out.println(head);
}

private ListNode reverse(ListNode head) {
ListNode cur = head;
ListNode pre = null;

while (cur != null) {
ListNode t = cur.next;
cur.next = pre;
pre = cur;
cur = t;
}

return pre;
}
}
-------------本文结束感谢您的阅读-------------
可以请我喝杯奶茶吗