ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

[LeetCode]143.重排链表

2026/8/15 0:17:20 拓冰建站 浏览量
[LeetCode]143.重排链表

143. 重排链表 - 力扣(LeetCode)icon-default.png?t=N7T8https://leetcode.cn/problems/reorder-list/description/

题目

 示例

 

 解题思路

 寻找链表中点 + 链表逆序 + 合并链表

注意到目标链表即为将原链表的左半端和反转后的右半端合并后的结果。

这样我们的任务即可划分为三步:

找到原链表的中点(参考 876. 链表的中间结点 - 力扣(LeetCode))。

我们可以使用快慢指针来 O(N) 地找到链表的中间节点。
将原链表的右半端反转(参考 206. 反转链表 - 力扣(LeetCode))。

我们可以使用迭代法实现链表的反转。
将原链表的两端合并(参考 21. 合并两个有序链表 - 力扣(LeetCode))

因为两链表长度相差不超过 1,因此直接合并即可。

代码

class Solution {
public:void reorderList(ListNode* head) {//处理边界情况if(head==nullptr || head->next==nullptr || head->next->next==nullptr) return;//找到链表的中间节点---快慢指针ListNode* fast=head,*slow=head;while(fast&&fast->next){fast=fast->next->next;slow=slow->next;}//2.把slow后面部分逆序ListNode* head2=new ListNode(0);//虚拟头节点,方便头插ListNode* cur=slow->next;ListNode* next=cur;slow->next=nullptr;//注意把两个链表断开while(cur){next=cur->next;cur->next=head2->next;//用next保存后,断开该节点原来和后面的链接,连上逆序后的最后一位节点head2->next=cur;cur=next;}//3.合并两个链表ListNode* ret=new ListNode(0);ListNode* pre=ret;ListNode* cur1=head,*cur2=head2->next;//head2是虚拟头节点while(cur1){pre->next=cur1;pre=pre->next;cur1=cur1->next;if(cur2){pre->next=cur2;pre=pre->next;cur2=cur2->next;}}delete head2;delete ret;}
};