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

解题思路:

(1)首先判断链表是否为空,是否只含有一个结点等。

(2)找到链表的中间结点,这个可以通过“快慢”指针的方法找到。然后就地逆置后半部分链表。

(3) 把前半部分的链表和逆置后的链表“逐一”串起来,即可AC此题。


C++代码如下:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseLinkList(ListNode* head){
        if(!head && !head->next)
            return head;
        
        ListNode* first, *second, *temp;
        first = head;
        second = head->next;
        
        while(second){
            temp = second->next;
                second->next = first;
            first = second;
            second = temp;
        }
        head->next = NULL;
        
        return first;
    }
    
    void reorderList(ListNode* head) {
        if(!head || !head->next){
            return;
        }
        
        ListNode* slow, *fast;
        slow = fast = head;
        while(fast && fast->next){
            slow = slow->next;
            fast = fast->next->next;
        }
        
        ListNode* tail = reverseLinkList(slow);
        ListNode* tempHead = head, *temp1, *temp2;
 
        while(tempHead && tempHead->next && tail && tail->next){
            temp1 = tempHead->next;
            tempHead->next = tail;
            temp2 = tail->next;
            tail->next = temp1;
            
            tempHead = temp1;
            tail = temp2;
        }
    }
};


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