Leetcode0143--Reorder List 鏈表重排

【轉載請註明】http://www.javashuo.com/article/p-wtjkdzop-cv.htmlhtml

具體的圖示可查看 連接node


 

代碼一spa

 

/**
 * 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;
        // two pointers split the list
        // 快慢指針,快指針到尾時,慢指針在前list尾部
        // example: 1->2->3->4->5 fast=5,slow=3, 1->2->3 & 4->5
        // example: 1->2->3->4    fast=3,slow=2, 1->2    & 3->4
        ListNode *slow = head, *fast = head;
        while(fast->next !=NULL && fast->next->next !=NULL){
            slow = slow ->next;
            fast = fast->next->next;
        }
        ListNode *head1 = head;
        // reverse the second list(with large numbers)
        // 翻轉第二個鏈表
        ListNode *head2 = reverseList(slow->next);
        slow->next = NULL;
        while(head2!=NULL){             // list1 size >= list2 size
            ListNode *next1 = head1->next;
            ListNode *next2 = head2->next;
            head1->next = head2;
            head2->next = next1;
            head1 = next1;
            head2 = next2;
        }
        if(head1!=NULL){
            head1->next = NULL;
        }
    }
    // reverse list
    ListNode *reverseList(ListNode *head){
        if(head==NULL || head->next ==NULL) return head;
        ListNode * new_head = NULL;
        while(head!=NULL){
            ListNode *pNext = head->next;
            head->next = new_head;
            new_head = head;
            head = pNext;
        }
        return new_head;
    }
};

 


/**
 * 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) {
        stack<ListNode* > nodestack;
        int length=0;
        // 計算鏈表長度,結點壓入stack
        ListNode *temp = head;
        while(temp){
            length++;
            nodestack.push(temp);
            temp = temp->next;
        }
        // 棧彈出,鏈接鏈表
        temp = head;
        int cnt = length/2;
        while(cnt){
            ListNode *head2 = nodestack.top();
            nodestack.pop();
            ListNode *headNext = temp->next;
            temp->next =head2;
            head2->next = headNext;
            temp = headNext;
            cnt--;
        }
        // 總數爲odd,temp指向末尾元素
        // 總數爲even,temp會和前元素重複,此處刪除
        if(length%2){
            temp->next = NULL;
        }else{
            temp = NULL;
        }
    }
};
相關文章
相關標籤/搜索