• 143 重排链表


    方法一 活用set

    void reorderList(ListNode *head) {
        if (head == nullptr || head->next == nullptr)
            return;
        set<ListNode *> save;
        int len = 1;
        ListNode *t = head;
        for (; t->next != nullptr; t = t->next)
            ++len;
        int mid = len % 2 == 0 ? len / 2 : (len + 1) / 2;
        t = head;
        for (; mid > 0; --mid)
            t = t->next;
        while (t != nullptr) {
            save.insert(t);
            t = t->next;
        }
        t = head;
        auto end = --save.end();
        for (auto size = save.size(); size > 0; --size) {
            (*end)->next = t->next;
            t->next = *end;
            t = t->next->next;
            --end;
        }
        t->next = nullptr;
    }
    

    方法二 快慢指针找中点然后反转后半部分链表,然后插入到前半个链表当中去

    ListNode *reverse(ListNode *head) {
        ListNode *front = head, *rear = nullptr, *temp = nullptr;
        while (front != nullptr) {
            temp = front->next;
            front->next = rear;
            rear = front;
            front = temp;
        }
        return rear;
    }
    
    void reorderList(ListNode *head) {
            if(head== nullptr||head->next== nullptr)
            return;
        auto *prehead = new ListNode(0);
        prehead->next = head;
        ListNode *fast = prehead, *slow = prehead;
        while (fast->next != nullptr) {
            fast = fast->next;
            slow = slow->next;
            if (fast->next == nullptr)
                break;
            fast = fast->next;
        }
        slow = reverse(slow->next);
        fast = head;
        while (slow != nullptr) {
            ListNode *temp = slow->next;
            slow->next = fast->next;
            fast->next = slow;
            slow = temp;
            fast = fast->next->next;
        }
        fast->next = nullptr;
    }
    
  • 相关阅读:
    在Xsheel Linux上安装nodejs和npm
    判断js中的数据类型的几种方法
    Sequelize 中文API文档-1. 快速入门、Sequelize类
    php中 ob_start()有什么作用
    PHP错误类型及屏蔽方法
    ajax对象的获取及其常用属性
    linux工作笔记
    Redis和Memcached的区别
    MySQL架构
    Http协议三次握手过程
  • 原文地址:https://www.cnblogs.com/INnoVationv2/p/10260229.html
Copyright © 2020-2023  润新知