【排序】链表上的归并排序

来源:互联网 发布:朱迪福斯特优秀 知乎 编辑:程序博客网 时间:2024/05/17 02:19

首先把链表搞成队列,每次合并两项队首压入队列,直到队列长度为1,出队得到结果链表。


#include <cstdlib>#include <cstdio>#include <queue>using namespace std;struct Node{    int value; Node *next;    void toString()    {        static char buff[100]; puts([&]() -> char *{ sprintf(buff, "[Node:0x%p @value=%4d @next=%p]", this, value, next); return buff; }());    }    void travel()    {        this->toString(); Node *x = next; while(x) x->toString(), x = x->next;    }};Node *gemerateList(int len = 10){    Node tmp{ 0, nullptr }; Node *t = &tmp;    for(int i = 0; i < len; ++i, t = t->next)    {        t->next = new Node{ rand() % 1000, nullptr };    }    return tmp.next;}Node *mergeList(Node *x, Node *y){    Node tmp; Node *z = &tmp;    auto pop_x = [&]() -> void { z->next = x; x = x->next; z = z->next; };    auto pop_y = [&]() -> void { z->next = y; y = y->next; z = z->next; };    while(x && y)    {        if(x->value < y->value) pop_x();        else                    pop_y();    }    if(x) z->next = x;    if(y) z->next = y;    return tmp.next;}Node* mergeSort(Node *L){    queue<Node*> *Q = new queue<Node*>;    for(Node *i = L, *j; i; i = j)    {        j = i->next; i->next = nullptr; Q->push(i);    }    auto legal_head = [&Q]() -> Node* { Node *tmp = Q->empty() ? nullptr : Q->front(); if(tmp) Q->pop(); return tmp; };    while(Q->size() > 1)    {        Q->push(mergeList(legal_head(), legal_head()));    }    return Q->empty() ? nullptr : Q->front();}int main(){    mergeSort(gemerateList(100))->travel();    return 0;}


0 0
原创粉丝点击