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


發佈了115 篇原創文章 · 獲贊 29 · 訪問量 48萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章