143. Reorder List

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

【思路】将链表分成前后两部分,对后一部分进行反转,再将前后依次链接。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head)
    {
       if (head==NULL || head->next==NULL) return head;  
        ListNode* ptr = NULL;  
        while(head !=NULL)  
        {  
            ListNode* L = new ListNode(head->val);  
            L->next = ptr;  
            ptr = L;  
            head = head->next;  
        }  
        return ptr;  
    }
    void reorderList(ListNode* head) {
        if(head==NULL||head->next==NULL)
                return ;
        ListNode *fast=head;
        ListNode *slow=head;
        ListNode *p;
        ListNode *p2;
        ListNode *t;
        ListNode *t2;

        while(fast&&fast->next&&fast->next->next)
        {
            fast=fast->next->next;
            slow=slow->next;
        }
        p2=slow->next;
        slow->next=NULL;
        p2= reverseList(p2);
        p=head;
        while(p&&p2)
        {
            t=p->next;
            t2=p2->next;
            p->next=p2;
            p->next->next=t;
            p=t;
            p2=t2;
        }
    }
};


你可能感兴趣的:(143. Reorder List)