zoukankan      html  css  js  c++  java
  • 单链表的归并排序

    #include<iostream>
    #include<time.h>
    using namespace std;
    
    
    //链表的归并排序
    struct listnode{
        int value;
        listnode* next;
        listnode(int value):value(value),next(NULL){}
    };
    
    listnode* find_mid(listnode* head){
        if(head==NULL)return NULL;
        listnode* fast=head;
        listnode* slow = head;
        while(fast->next!=NULL){
            if(fast->next->next!=NULL){
                fast = fast->next->next;
                slow = slow->next;
            }else
                break;
        }
        return slow;
    }
    
    listnode* merge_list(listnode* list1,listnode* list2){
        if(list1==NULL)return list2;
        if(list2==NULL)return list1;
        listnode* cur = NULL;
        listnode* head=NULL;
        if(list1->value<=list2->value){
            head = list1;
            list1 = list1->next;
        }else{
            head = list2;
            list2 = list2->next;
        }
        listnode* pnode = head;
        while(list1&&list2){
            if(list1->value<=list2->value){
                cur = list1;
                list1 = list1->next;
            }else{
                cur = list2;
                list2 = list2->next;
            }
            pnode->next = cur;
            pnode = pnode->next;
        }
        if(list1 == NULL)pnode->next = list2;
        if(list2 == NULL)pnode->next = list1;
        return head;
    }
    
    listnode* merge_sort(listnode* head){
        if(head==NULL||head->next==NULL)return head;
        listnode* mid = find_mid(head);
        listnode* m = mid->next;
        mid->next = NULL;
        listnode* list1 = merge_sort(head);
        listnode* list2 = merge_sort(m);
        head = merge_list(list1,list2);
        return head;
    }
    int main(){
        int length = 10;
        listnode* r = new listnode(0);
        listnode* head = r;
        for(int i=0;i<length;i++){
            r->next = new listnode(rand()%30);
            r = r->next;
        }
        listnode* p = merge_sort(head->next);
        delete head;
        head= p;
        while(head){
            listnode* temp = head;
            head = head->next;
            cout<<temp->value<<endl;
            delete temp;
        }
        system("pause");
    }
  • 相关阅读:
    kafka_consumer3->spark_master
    为什么.NET感觉上比Java差一点
    学习Scala: 初学者应该了解的知识
    函数式编程 : 一个程序猿进化的故事
    Scala underscore的用途
    不变(Invariant), 协变(Covarinat), 逆变(Contravariant) : 一个程序猿进化的故事
    Scala Collection简介
    C# on Visual Studio Code
    我的Machine Learning学习之路
    Scala on Visual Studio Code
  • 原文地址:https://www.cnblogs.com/zhang-wen/p/4796253.html
Copyright © 2011-2022 走看看