【LeetCode】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}.


思路:

        先利用快慢指针找到链表中点,这个中点也是重排之后的尾结点。找到中点之后将链表分为前后两个链表,再将后面的链表逆序,然后依次从两个链表中取出头结点组成新的链表


class Solution {
public:
    void reorderList(ListNode *head) {
        if (!head || !head->next || !head->next->next) { 
            return;
        }

        // find the last and median nodes 
        ListNode *slow, *fast;
        slow = fast = head;
        while (fast != NULL) {
            if (fast->next != NULL) {
                slow = slow->next;
                fast = fast->next->next;
            } else {
                break; 
            }
        }

        ListNode *prev, *curr, *succ;
        
        prev = slow->next;
        curr = prev->next; 
        succ = curr ? curr->next : NULL;
        
        prev->next = NULL;
        slow->next = NULL;

        // reverse list
        while (succ != NULL) {
            curr->next = prev;
            prev = curr;
            curr = succ;
            succ = succ->next;
        }

        // reverse the last two nodes
        if (curr == NULL) { // there only 1 node in list.
            curr = prev;
        } else { 
            curr->next = prev;
        }

        ListNode *head_1 = head->next;
        ListNode *head_2 = curr;
        ListNode *tail = head;
        
        // merge two lists
        while (head_1 && head_2) {
            tail->next = head_2; head_2 = head_2->next;
            tail = tail->next;

            tail->next = head_1; head_1 = head_1->next;
            tail = tail->next;
        }
        
        tail->next = head_1 ? head_1 : (head_2 ? head_2 : NULL);
    }
};


你可能感兴趣的:(LeetCode,链表)