【LeetCode】143. Reorder List

Reorder List

Given a singly linked list LL0→L1→…→Ln-1→Ln,
reorder it to: L0→LnL1→Ln-1→L2→Ln-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}.

解题思路:

step1:将链表均分成两半。(即用fast&slow指针找出中间节点,切断即可。)

step2:将后半链表逆序。

step3:交替插入。

/**
 * 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 || head->next == NULL)
            return;

        ListNode* fast = head;
        ListNode* slow = head;
        ListNode* preslow = NULL;
        while(fast != NULL)
        {
            fast = fast->next;
            if(fast != NULL)
            {
                fast = fast->next;
                preslow = slow;
                slow = slow->next;
            }
        }
        ListNode* newhead = new ListNode(-1);
        ListNode* newtail = newhead;

        ListNode* head1 = head;
        ListNode* head2 = reverse(slow);
        preslow->next = NULL;

        while(head1 != NULL && head2 != NULL)
        {
            newtail->next = head1;
            head1 = head1->next;
            newtail = newtail->next;

            newtail->next = head2;
            newtail = newtail->next;
            head2 = head2->next;
        }
        if(head1 != NULL)
            newtail->next = head1;
        if(head2 != NULL)
            newtail->next = head2;
        head = newhead->next;
    }
    ListNode* reverse(ListNode* head)
    {
        if(head == NULL)
            return NULL;
        else if(head->next == NULL)
            return head;
        else if(head->next->next == NULL)
        {
            ListNode* tail = head->next;
            tail->next = head;
            head->next = NULL;
            return tail;
        }
        else
        {
            ListNode* pre = head;
            ListNode* cur = pre->next;
            ListNode* post = cur->next;
            while(post != NULL)
            {
                cur->next = pre;
                pre = cur;
                cur = post;
                post = post->next;
            }
            cur->next = pre;
            head->next = NULL;
            return cur;
        }
    }
};

原文地址:https://www.cnblogs.com/ganganloveu/p/4065262.html