重排链表
难度:
标签:
题目描述
English description is not available for the problem. Please switch to Chinese.
代码结果
运行时间: 33 ms, 内存: 21.4 MB
/*
题目思路:
由于Java Stream不适用于链表操作,因此我们只能使用传统方法。
本方法同上Java解法。
*/
public class Solution {
public void reorderList(ListNode head) {
if (head == null || head.next == null) return;
// Step 1: Find the middle of the list
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
// Step 2: Reverse the second half
ListNode prev = null, curr = slow, temp;
while (curr != null) {
temp = curr.next;
curr.next = prev;
prev = curr;
curr = temp;
}
// Step 3: Merge the two halves
ListNode first = head, second = prev;
while (second.next != null) {
temp = first.next;
first.next = second;
first = temp;
temp = second.next;
second.next = first;
second = temp;
}
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
解释
方法:
题解分为三个主要部分:1. 使用快慢指针找到链表的中间节点,从而将链表分为前半部和后半部。2. 反转链表的后半部分。3. 将反转后的后半部分交替插入前半部分中,从而达到题目要求的重排。快慢指针技巧用于高效找到链表中点,链表反转则是常规操作,最后的合并需要细心操作节点指针以避免丢失或混乱。
时间复杂度:
O(n)
空间复杂度:
O(1)
代码细节讲解
🦆
为什么在找到链表中点后,需要将链表从中间断开成两个部分?
▷🦆
在反转链表的函数`reverList`中,为何设定`pre`为`None`,这是如何帮助完成链表反转的?
▷🦆
如何确保在反转后半部的链表时不会丢失原链表的数据?
▷