首页 > 代码库 > 143. Reorder List

143. Reorder List

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

/**
 * 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) {
        if(!head||!head->next)return ;
        ListNode* fast=head,*slow=head;
        //找到中间结点
        while(fast->next&&fast->next->next){
            fast=fast->next->next;
            slow=slow->next;
        }
        //反转后半部分
        slow=reverse(slow->next);
        //交叉插入,得到结果
        fast=head;
        while(slow){
            ListNode* slowNext=slow->next;
            slow->next=fast->next;
            fast->next=slow;
            fast=slow->next;
            slow=slowNext;
        }
        //最后置空,否则会使得链表永不停息。
        fast->next=NULL;
    }
    ListNode* reverse(ListNode* head){
        ListNode* p=head->next,*next;
        head->next=NULL;
        while(p){
            next=p->next;
            p->next=head;
            head=p;
            p=next;
        }
        return head;
    }
};

 

143. Reorder List