Leetcode143. 重排链表 -春招冲刺

该篇文章介绍了如何使用C++中的Solution类中的reorderList方法,通过unordered_map数据结构来重排链表节点,确保链表在特定条件下正确地进行顺序调整。
摘要由CSDN通过智能技术生成

题目:


代码(首刷自解 2024年4月11日):

class Solution {
public:
    void reorderList(ListNode* head) {
        if (!head) return;
        // 用一个hash存储下表对应的节点
        unordered_map<int, ListNode*> index_to_node;
        ListNode* cur = head;
        int index = 0;
        while(cur) {
            index_to_node[index++] = cur;
            cur = cur->next;
        }
        // 根据下表重排链表
        int i, j;
        for (i = 0, j = index - 1; i < j; ) {
            index_to_node[i++]->next = index_to_node[j];
            if (i >= j)  break;
            index_to_node[j--]->next = index_to_node[i];
        }
        index_to_node[i]->next = nullptr;//很重要,循环结束要置空,不然会循环链表
    }
};

代码(二刷看解析 2024年8月6日)

看的林茶山大佬的

class Solution {
private:
    ListNode* mid(ListNode* head) {
        auto fast = head;
        auto slow = head;
        while (fast && fast->next) {
            fast = fast->next->next;
            slow = slow->next;
        }
        return slow;
    }
    ListNode* reverseNode(ListNode* head) {
        ListNode* pre = nullptr;
        auto cur = head;
        while (cur) {
            auto nxt = cur->next;
            cur->next = pre;
            pre = cur;
            cur = nxt;
        }
        return pre;
    }
public:
    void reorderList(ListNode* head) {
        auto midNode = mid(head);
        auto head2 = reverseNode(midNode);
        while (head2->next) {
            auto nxt = head->next;
            auto nxt2 = head2->next;
            head->next = head2;
            head2->next = nxt;
            head = nxt;
            head2 = nxt2;
        }
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值