LeetCode(M) Sort List

Sort a linked list in O(n log n) time using constant space complexity.

根據題目O(nlogn)時間,O(1)空間,選擇了歸併排序

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* sortList(ListNode* head) {
       if(!head) return NULL;
       if(!head->next) return head;
       // ListNode*pre=new ListNode(-1);
       /* pre->next=head;
        ListNode *fast=pre->next,*slow=pre->next->next;
        while(slow->next&&slow->next->next){
            fast=fast->next;
            slow=slow->next->next;
        }
        fast->next=NULL;*/
        ListNode *slow = head, *fast = head, *pre = head;
         while (fast && fast->next) {
            pre = slow;
            slow = slow->next;
            fast = fast->next->next;
        }
        pre->next = NULL;
    //   sortList(fast);sortList(slow);
     //   return  merge(fast,slow); 
  //   sortList(head);sortList(slow);
   //  return merge(head,slow);
     return merge(sortList(head), sortList(slow));
    }

    ListNode* merge(ListNode* first,ListNode *second){

        ListNode *temp=new ListNode(-1),*p=first,*q=second,*pre;
        pre=temp;
        while(p&&q){
        if(p->val>q->val) {temp->next=q;q=q->next;}
        else{temp->next=p;p=p->next;}
        temp=temp->next;
        }
        if(p) temp->next=p;//這裏由while改成了if
       if(q) temp->next=q;
        return pre->next;
    }
    };

打了註釋的地方都是錯誤點

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章