Sunday, November 3, 2013

Reorder List [Leetcode]

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

Solution: nothing but pointer manipulation.
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *reverse(ListNode* head){
        ListNode* prev = NULL;
        ListNode* cur=head;
        while(cur!=NULL){
            ListNode* next = cur->next;
            cur->next = prev;
            prev = cur;
            cur = next;
        }
        return prev;
    }
    void reorderList(ListNode *head) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if(head==NULL || head->next==NULL || head->next->next==NULL)
            return;
        ListNode* slow = head;
        ListNode* fast = head;
        ListNode* tail = NULL;
        //Find the (nNode/2)-th node, the new tail
        while(fast!=NULL && fast->next!=NULL){
            tail = slow;
            slow=slow->next;
            fast=fast->next->next;
        }
        if(fast!=NULL)
            tail = tail->next;
        //Reverse the second part
        ListNode *sHead = reverse(tail->next);
        tail->next = NULL;
        //Combination
        ListNode* sCur = sHead;
        ListNode* cur = head;
        while(sCur!=NULL){
            ListNode* nxt = cur->next;
            ListNode* sNxt = sCur->next;
            cur->next = sCur;
            sCur->next = nxt;
            cur=nxt;
            sCur=sNxt;
        }
    }
};

No comments:

Post a Comment