zoukankan      html  css  js  c++  java
  • 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;
    }
    
  • 相关阅读:
    398. Random Pick Index
    382. Linked List Random Node
    645. Set Mismatch
    174. Dungeon Game
    264. Ugly Number II
    115. Distinct Subsequences
    372. Super Pow
    LeetCode 242 有效的字母异位词
    LeetCode 78 子集
    LeetCode 404 左叶子之和
  • 原文地址:https://www.cnblogs.com/INnoVationv2/p/10260229.html
Copyright © 2011-2022 走看看