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;
        }
        
        ListNode *p = head;
        int len = 0;
        while (p)
        {
            len++;
            p = p->next;
        }

        int steps = (len-1)/2;
        p = head;
        while (steps)
        {
            p = p->next;
            steps--;
        }

        ListNode *q = p->next;
        p->next = NULL;
        ListNode *prev = NULL;
        while (q)
        {
            ListNode *r = q->next;
            q->next = prev;
            prev = q;
            q = r;
        }

        p = head;
        q = prev;

        while (q)
        {
            ListNode *firstTemp = p->next;
            ListNode *secondTemp = q->next;
            p->next = q;
            q->next = firstTemp;
            p = firstTemp;
            q = secondTemp;
        }
    }
};


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