leetcode系列(71)Reorder List

来源:互联网 发布:酷家乐云设计软件 编辑:程序博客网 时间:2024/05/16 01:39

Given a singly linked list LL0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-2→…

You must do this in-place without alteringthe nodes' values.

For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.

解答:1. 用快慢指针split链表为两个,2. 逆序第二链表,3.安装要求拼接两个链表。

class Solution {public:    void reorderList(ListNode* head) {        if (head == nullptr) {            return;        }        auto slow = head;        auto fast = head->next;        while (fast != nullptr && fast->next != nullptr) {            slow = slow->next;            fast = fast->next->next;        }        auto list1 = head;        //ListNode* list2 = nullptr;        //_reverse_1(slow->next, &list2);        ListNode* list2 = _reverse_2(slow->next, nullptr);        slow->next = nullptr;        while (list2 != nullptr) {            auto tmp = list2->next;            list2->next = list1->next;            list1->next = list2;            list1 = list1->next->next;            list2 = tmp;        }    }private:    void _reverse_1(ListNode* head, ListNode** ret) {        if (head != nullptr) {            auto tmp = head->next;            head->next = *ret;            *ret = head;            _reverse_1(tmp, ret);        }    }        ListNode* _reverse_2(ListNode* head, ListNode* ret) {        if (head == nullptr) {            return ret;        } else {            auto tmp = head->next;            head->next = ret;            ret = head;            return _reverse_2(tmp, ret);        }    }};


0 0