143. 重排链表
题目描述
给定一个单链表 L
的头节点 head
,单链表 L
表示为:
L0 → L1 → … → Ln - 1 → Ln
请将其重新排列后变为:
L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
输入:head = [1,2,3,4] 输出:[1,4,2,3]
示例 2:
输入:head = [1,2,3,4,5] 输出:[1,5,2,4,3]
提示:
- 链表的长度范围为
[1, 5 * 104]
1 <= node.val <= 1000
方法一:快慢指针 + 反转链表 + 合并链表
我们先用快慢指针找到链表的中点,然后将链表的后半部分反转,最后将左右两个链表合并。
时间复杂度
java
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;
}
// cur 指向右半部分链表
ListNode cur = slow.next;
slow.next = null;
// 反转右半部分链表
ListNode pre = null;
while (cur != null) {
ListNode t = cur.next;
cur.next = pre;
pre = cur;
cur = t;
}
cur = head;
// 此时 cur, pre 分别指向链表左右两半的第一个节点
// 合并
while (pre != null) {
ListNode t = pre.next;
pre.next = cur.next;
cur.next = pre;
cur = pre.next;
pre = t;
}
}
}
cpp
class Solution {
public:
void reorderList(ListNode* head) {
// 快慢指针找到链表中点
ListNode* fast = head;
ListNode* slow = head;
while (fast->next && fast->next->next) {
slow = slow->next;
fast = fast->next->next;
}
// cur 指向右半部分链表
ListNode* cur = slow->next;
slow->next = nullptr;
// 反转右半部分链表
ListNode* pre = nullptr;
while (cur) {
ListNode* t = cur->next;
cur->next = pre;
pre = cur;
cur = t;
}
cur = head;
// 此时 cur, pre 分别指向链表左右两半的第一个节点
// 合并
while (pre) {
ListNode* t = pre->next;
pre->next = cur->next;
cur->next = pre;
cur = pre->next;
pre = t;
}
}
};
ts
/**
Do not return anything, modify head in-place instead.
*/
function reorderList(head: ListNode | null): void {
let slow = head;
let fast = head;
// 找到中心节点
while (fast && fast.next) {
slow = slow.next;
fast = fast.next.next;
}
// 反转节点
let next = slow.next;
slow.next = null;
while (next) {
[next.next, slow, next] = [slow, next, next.next];
}
// 合并
let left = head;
let right = slow;
while (right.next) {
const next = left.next;
left.next = right;
right = right.next;
left.next.next = next;
left = left.next.next;
}
}
python
class Solution:
def reorderList(self, head: Optional[ListNode]) -> None:
# 快慢指针找到链表中点
fast = slow = head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
# cur 指向右半部分链表
cur = slow.next
slow.next = None
# 反转右半部分链表
pre = None
while cur:
t = cur.next
cur.next = pre
pre, cur = cur, t
cur = head
# 此时 cur, pre 分别指向链表左右两半的第一个节点
# 合并
while pre:
t = pre.next
pre.next = cur.next
cur.next = pre
cur, pre = pre.next, t