143. Reorder List

143. Reorder List

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

 

思路:首先用双指针找到中间节点,截断为left和right。然后将中间断开,将right反转,再利用归并算法将两者合并。

不要需要注意

while(left != nullptr && right != nullptr){
            
            dummyNode -> next = left;
            dummyNode = dummyNode -> next;
            //left = left -> next;
            cout << dummyNode -> val << endl;
            
            dummyNode -> next = right; 
            left = left -> next;
            
            cout << left -> val << endl;
            dummyNode = dummyNode -> next; 
            right = right -> next;             
            
        }

这里left = left -> next放置位置不同,会有不同结果,放在上面是没有问题的。

放在下面就变为死循环,原因就是上面的图。

 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverse(ListNode*  head){
        if(head == nullptr){
            return head;
        }
        ListNode* pre = nullptr;
        ListNode* cur = head;;
        ListNode* post = cur -> next;
        while(cur != nullptr){
            post = cur -> next;
            cur -> next = pre;
            pre = cur;
            cur = post;
        }
        return pre;
    }
    
    ListNode* findMid(ListNode* head){
        if(head == nullptr || head -> next == nullptr){
            return head;
        }
        ListNode* fast = head -> next;
        ListNode* slow = head;
        while(fast != nullptr && fast -> next != nullptr){
            fast = fast -> next -> next;
            slow = slow -> next;
        }
        return slow;
    }
    
    void reorderList(ListNode* head) {
        if(head == nullptr || head -> next == nullptr){
            return;
        }
        
        ListNode* mid = findMid(head);        
        ListNode* right = mid -> next;
        mid -> next = nullptr;
        
        right = reverse(right);
        
        ListNode* dummyNode = new ListNode(0);
        dummyNode -> next = head;
        
        ListNode* pHead = dummyNode;
        ListNode* left = head;
        
        ListNode*pleft = left;
        ListNode* pright = right;
        
        while(left != nullptr && right != nullptr){
            
            dummyNode -> next = left;
            dummyNode = dummyNode -> next;
            left = left -> next;
            
            dummyNode -> next = right; 
            dummyNode = dummyNode -> next; 
            right = right -> next;             
            
        }
        if(left != nullptr){
            dummyNode -> next = left;
            
        }
        if(right != nullptr){
            dummyNode -> next = right;
        }
        head = pHead -> next;
    }
};

 

posted @ 2017-09-27 14:07  zqlucky  阅读(184)  评论(0编辑  收藏  举报