[leetcode]143. Reorder List

来源:互联网 发布:mac桌面文件路径 编辑:程序博客网 时间:2024/06/05 01:13

题目链接:https://leetcode.com/problems/reorder-list/#/description

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}.


class Solution {public:    void reorderList(ListNode *head) {        if (!head || !head->next) return;        // find the middle node: O(n)        ListNode *p1 = head, *p2 = head->next;        while (p2 && p2->next) {            p1 = p1->next;            p2 = p2->next->next;        }        // cut from the middle and reverse the second half: O(n)        ListNode *head2 = p1->next;        p1->next = NULL;        p2 = head2->next;        head2->next = NULL;        while (p2) {            p1 = p2->next;            p2->next = head2;            head2 = p2;            p2 = p1;        }        // merge two lists: O(n)        for (p1 = head, p2 = head2; p1; ) {            auto t = p1->next;            p1 = p1->next = p2;            p2 = t;        }    }};


原创粉丝点击