栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++ 实现归并排序(使用单链表)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++ 实现归并排序(使用单链表)

#include 
#include 
using namespace std;


struct Linklist {
    int val;
    Linklist* next;
    Linklist() {next = nullptr;}
    Linklist(int v) {val = v; next = nullptr;}
};
Linklist* link(vector arr) {
    int n = arr.size();
    Linklist* head = new Linklist;
    Linklist* temp = head;
    for (int i = 0; i < n; i++) {
        temp->val = arr[i];
        if (i != n - 1) {
            temp->next = new Linklist;
            temp = temp->next;
        }
    }
    return head;
} 
void display(Linklist* head) {
    while (head) {
        cout << head->val << " ";
        head = head->next;
    }
    cout << endl;
}
Linklist* merge(Linklist* lhead, Linklist* rhead) {
    Linklist* head = new Linklist;
    Linklist* temp = head;
    Linklist* temp1 = lhead;
    Linklist* temp2 = rhead;
    while (temp1 && temp2) {
        if (temp1->val < temp2->val) {
            temp->next = temp1;
            temp1 = temp1->next;
        } else {
            temp->next = temp2;
            temp2 = temp2->next;
        }
        temp = temp->next;
    }
    if (temp1)
        temp->next = temp1;
    if (temp2)
        temp->next = temp2;
    return head->next;
}
Linklist* merge_sort(Linklist* head) {
    // 用快慢指针确定中点
    Linklist *quick, *slow;
    quick = slow = head;
    while (quick->next) {
        quick = quick->next;
        if (quick->next) {
            quick = quick->next;
            slow = slow->next;
        }
    }
    // 链表只有一个节点,直接返回
    if (quick == slow)
        return head;
    // 将链表切分为两段
    Linklist* lhead = head;
    Linklist* rhead = slow->next;
    slow->next = nullptr;
    lhead = merge_sort(lhead);
    rhead = merge_sort(rhead);
    head = merge(lhead, rhead);
    return head;
}

int main() {
    vector arr = {3,8,1,9,2,11,15,22,0,87};
    Linklist* head = link(arr);
    head = merge_sort(head);
    display(head);

    return 0;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/982927.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号