leetcode.143. Reorder List

Given a singly linked list L: L0L1→…→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:
    void reorderList(ListNode* head) {
        if(head==NULL)   return;
        if(head->next==NULL)   return;
        if(head->next->next==NULL)  return;
        
        ListNode* pMid = findMid(head);
        ListNode* slow = reverse(pMid);
        ListNode* fast = head;
        ListNode* prefast;
        ListNode* preslow;
        while(fast!=NULL&&fast->next!=NULL&&slow!=NULL&&slow->next!=NULL)
        {
            prefast = fast;
            preslow = slow;
            fast = fast->next;
            slow = slow -> next;
            prefast->next = preslow;
            preslow ->next = fast;
             
        }
        if(slow!=NULL)
        {
            fast->next = slow;
        }
        return;
        
    }
    ListNode* findMid(ListNode * head)
    {
        ListNode* fast = head;
        ListNode* slow = head;
        ListNode* pre;
        
        
        while(fast!=NULL)
        {
            fast = fast->next;
            if(fast!=NULL)
            {
                pre = slow;
                fast = fast->next;
                slow = slow->next;
            }
        }
        pre->next = NULL;
        return slow;
    }
    ListNode* reverse(ListNode* pMid)
    {
        ListNode* p = pMid;  
        ListNode* q = pMid->next;  
        ListNode* r = NULL;  
        while (q != NULL) {  
            r = q->next;  
            q->next = p;  
            p = q;  
            q = r;  
        }  
        pMid->next = NULL; // new tail  
        pMid = p; //new head;
        return pMid;
    }
};


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