C++ | Leetcode C++题解之第143题重排链表

题目:

题解:

cpp 复制代码
class Solution {
public:
    void reorderList(ListNode* head) {
        if (head == nullptr) {
            return;
        }
        ListNode* mid = middleNode(head);
        ListNode* l1 = head;
        ListNode* l2 = mid->next;
        mid->next = nullptr;
        l2 = reverseList(l2);
        mergeList(l1, l2);
    }

    ListNode* middleNode(ListNode* head) {
        ListNode* slow = head;
        ListNode* fast = head;
        while (fast->next != nullptr && fast->next->next != nullptr) {
            slow = slow->next;
            fast = fast->next->next;
        }
        return slow;
    }

    ListNode* reverseList(ListNode* head) {
        ListNode* prev = nullptr;
        ListNode* curr = head;
        while (curr != nullptr) {
            ListNode* nextTemp = curr->next;
            curr->next = prev;
            prev = curr;
            curr = nextTemp;
        }
        return prev;
    }

    void mergeList(ListNode* l1, ListNode* l2) {
        ListNode* l1_tmp;
        ListNode* l2_tmp;
        while (l1 != nullptr && l2 != nullptr) {
            l1_tmp = l1->next;
            l2_tmp = l2->next;

            l1->next = l2;
            l1 = l1_tmp;

            l2->next = l1;
            l2 = l2_tmp;
        }
    }
};
相关推荐
会周易的程序员21 分钟前
软件接入大模型实现 Agent —— 从原理到 C++ 落地完全指南
c++·人工智能·物联网·架构·agent·工业协议·mcp
hetao173383739 分钟前
2026-08-21~23 hetao1733837 的刷题记录
c++·算法
青 春 记 忆1 小时前
LeetCode 206. 反转链表|Python 解法详解
python·leetcode·链表
青 春 记 忆3 小时前
LeetCode 226. 翻转二叉树|Python 解法详解
python·算法·leetcode
Brilliantwxx3 小时前
【Linux】 进程(5) 僵尸进程与内存泄漏扩展
linux·运维·服务器·网络·c++
程与留4 小时前
08_对话框系统全解析——模态非模态、QMessageBox、QFileDialog
c++·qt
程序员的园4 小时前
赋值运算符为什么要避免自赋值?
c++
Escalating_xu4 小时前
【C++ vector 深度解析】从常用接口、扩容机制与迭代器失效到核心模拟实现
java·c++·面试
啊嘞嘞?4 小时前
力扣(回文链表)
算法·leetcode·链表