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

===============

思路:

按照slow/fast方法找到链表的中间结点mid,

此时中间节点将链表分为head1和head2,

将head2链表按照revOnPlace(ListNode *head)就地逆置,

遍历head1和head2两个链表,依次将head2链表中节点插入倒head1当中.

此题就是麻烦,需要辅助函数showList(ListNode *head)调试.

code如下:

/**
 * 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==nullptr || head->next==nullptr) return;
        ListNode *slow, *fast;
        ListNode *prev;
        slow = fast = head;
        prev = nullptr;
        while(fast && fast->next)
        {
            prev = slow;
            slow = slow->next;
            fast = fast->next->next;
        }
        ListNode *head2 = prev->next;
        prev->next = nullptr;

        head2 = revOnPlace(head2);
        //cout<<"head1: ";showList(head);
        //cout<<"head2: ";showList(head2);

        ListNode *head1 = head;
        slow = head1;
        fast = head2;
        while(slow && fast){
            ListNode *t1 = slow->next;
            ListNode *t2 = fast->next;
            head1->next = slow;
            head1->next->next = fast;
            head1 = fast;
            slow = t1;
            fast = t2;
        }
        //cout<<"done";showList(head);
    }
    
    ListNode* revOnPlace(ListNode *head)
    {
        ListNode dummy(-1);
        ListNode *curr = head;

        head = &dummy;
        while(curr)
        {
            ListNode *tmp = curr->next;
            curr->next = head->next;
            head->next = curr;
            curr = tmp;
        }

        return dummy.next;
    }
};
原文地址:https://www.cnblogs.com/li-daphne/p/5606933.html