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;
        }
    }
};
相关推荐
smj2302_796826521 天前
解决leetcode第3753题范围内总波动值II
python·算法·leetcode
散峰而望1 天前
C++数组(二)(算法竞赛)
开发语言·c++·算法·github
leoufung1 天前
LeetCode 92 反转链表 II 全流程详解
算法·leetcode·链表
利刃大大1 天前
【动态规划:背包问题】完全平方数
c++·算法·动态规划·背包问题·完全背包
笑非不退1 天前
C# c++ 实现程序开机自启动
开发语言·c++·c#
im_AMBER1 天前
Leetcode 59 二分搜索
数据结构·笔记·学习·算法·leetcode
leoufung1 天前
LeetCode 61. 旋转链表(Rotate List)题解与思路详解
leetcode·链表·list
AA陈超1 天前
从0开始学习 **Lyra Starter Game** 项目
c++·笔记·学习·游戏·ue5·lyra
q***T5831 天前
C++在游戏中的Unreal Engine
c++·游戏·虚幻
保持低旋律节奏1 天前
C++——C++11特性
开发语言·c++·windows