Leetcode SortList

OpenSoucre發表於2014-06-18

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

本題利用歸併排序即可

歸併排序的核心是將兩部分合成一部分,

故開始要將連結串列分成兩部分,利用快慢兩個指標,當快指標跑到連結串列尾部時,慢指標恰好在中間,故可以將連結串列分成兩部分

然後將兩個連結串列合併,注意可以新建一個新節點,作為連結串列頭結點,利用new新建節點後,要注意用delete刪除節點,保持良好的程式設計習慣

#include <iostream>
#include <vector>

using namespace std;

struct ListNode{
    int val;
    ListNode *next;
    ListNode(int x):val(x), next(NULL){}
};

void printList(ListNode* head){
    while(head!=NULL){
        cout<<"->"<<head->val;
        head = head->next;
    }
    cout<<endl;
}

ListNode *merge(ListNode *head1, ListNode *head2){
    // cout<<"======"<<endl;
    // printList(head1);
    // printList(head2);
    // cout<<"----->"<<endl;
    if(head1 == NULL ) return head2;
    if(head2 == NULL)  return head1;
    ListNode *mergeHead = new ListNode(-1);
    ListNode *pre = mergeHead;
    mergeHead->next = head1;
    while(head1!=NULL && head2 != NULL){
        if(head1->val < head2->val) head1= head1->next;
        else{
            ListNode *node = head2->next;
            head2->next = pre->next;
            pre->next = head2;
            head2 = node;
        }
        pre = pre->next;
    }
    if(head2!=NULL) pre->next = head;
    ListNode *res = mergeHead->next;
    delete mergeHead;
    return res;    
} 

ListNode *mergeSort(ListNode *head){
    if(head == NULL || head->next == NULL) return head;
    ListNode *slow = head;
    ListNode *fast = head;
    while(fast->next != NULL && fast->next->next != NULL){
        slow = slow->next;
        fast = fast->next->next;
    }
    ListNode* head2 = slow->next;
    slow->next = NULL;
    ListNode* head1 = head;
    head1 = mergeSort(head1);
    head2 = mergeSort(head2);
    return merge(head1,head2);
}

ListNode *sortList(ListNode *head){
    return mergeSort(head);
}

int main(){
    ListNode* head = new ListNode(3);
    ListNode* node1 = new ListNode(2);
    ListNode* node2 = new ListNode(4);
    head->next = node1;
    node1->next = node2;
    ListNode *a = sortList(head);
    cout<<"ans:"<<endl;
    printList(a);
}

本題更復雜一點的是

給出兩個無序連結串列,然後將其合併,

首先要做的事將無序連結串列排序,然後將兩個有序連結串列合併

相關文章