Saturday, April 25, 2015

[LeetCode] 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 *reverse(ListNode *p)
    {
        ListNode *ret = NULL;
        while(p)
        {
            ListNode * t =p->next;
            p->next = ret;
            ret = p;
            p = t;
        }
        return ret;
    }

    void reorderList(ListNode *head) {
        if(!head) return;
        int c = 0;
        ListNode *p = head, *m=head;
        ListNode *prev = head;
        while(p)
        {
            p=p->next;
            c++;
            if(c%2==0)
            {
                prev = m;
                m=m->next;
            }
        }
        if(c<=2) return;
        
        prev->next = NULL;
        ListNode *r = reverse(m);
        p = head;
        ListNode dummy(0);
        ListNode *ret = &dummy;
        c = 0; 
        while(p&&r)
        {
            if(c%2 ==0)
            {
                ret->next = p;
                ret = p;
                p = p->next;
            }
            else
            {
                ret->next = r;
                ret = r;
                r = r->next;
            }
            c++;
        }
        if(p) ret->next = p;
        else ret->next = r;
    }
};