leetcode第143题 ( Reorder List),快慢指针的应用

来源:互联网 发布:网络女主播是做什么的 编辑:程序博客网 时间:2024/06/06 00:11

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

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

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

代码如下:

void reorderList(ListNode* head) {        // cut list   1->2->3->4->5 ==> list1:1->2 list2:3->4->5        ListNode *fast = head, *slow = nullptr;        while (fast != nullptr && fast->next != nullptr) {        fast = fast->next->next;        slow = slow == nullptr ? head : slow->next;        }        if (slow == nullptr) return;        ListNode *head2 = slow->next;        slow->next = nullptr;        // reverse list2  3->4->5  ==>  5->4->3        slow = fast = head2;        head2 = nullptr;        while (fast != nullptr) {            fast = fast->next;        slow->next = head2;        head2 = slow;        slow = fast;        }        // merge two list  list1:1->2 list2:5->4->3  ==> 1->5->2->4->3        slow = fast = head;        while (fast != nullptr && head2 != nullptr) {        fast = fast->next;        slow->next = head2;        head2 = head2->next;        slow->next->next = fast ? fast : head2;        slow = fast;        }    }


0 0
原创粉丝点击