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");
    }
  • 相关阅读:
    -bash: belts.awk: command not found
    PLS-00357: Table,View Or Sequence reference 'SEQ_TRADE_RECODE.NEXTVAL' not allowed in this context
    初识makefile
    proc:基本数据库操作
    ORA-12154: TNS:could not resolve the connect identifier specified
    简单的爬虫
    合并一个文文件夹下的所有Excel文件
    Python 递归读取文件夹内所有文件名(包含子文件夹)
    CSS
    JQ
  • 原文地址:https://www.cnblogs.com/zhang-wen/p/4796253.html
Copyright © 2011-2022 走看看