Reorder List

来源:互联网 发布:新手淘宝店课程免费 编辑:程序博客网 时间:2024/05/16 10:06

题目链接

原题

Given a singly linked list L: L0→L1→…→Ln-1→Ln,reorder it to: L0→Ln→L1→Ln-1→L2→Ln-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}.

思路

1 找到链表的后半部分, 然后反转后半部分.2 类似归并排序的做法, 改变前部分链表和反转的后半部分链表的指向即可.

code

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    void reorderList(ListNode* head) {        const ListNode* null = NULL;        if(head == null || head->next == null) return;        // find the half list        ListNode* slow = head;        ListNode* fast = head;        while(fast->next != null && fast->next->next != null) {            slow = slow->next;            fast = fast->next->next;        }        // reverse        ListNode* p = NULL;        while(slow) {            ListNode* tmp = slow->next;            slow->next = p;            p = slow;            slow = tmp;        }        // reorder        ListNode* p2 = head;        while(p && p2) {            ListNode* t1 = p2->next;            ListNode* t2 = p->next;            p2->next = p;            p->next = t1;            p2 = t1;            p = t2;        }        return;    }};
0 0