【链表】链表上的插入排序

来源:互联网 发布:鲁荣渔2682惨案 知乎 编辑:程序博客网 时间:2024/05/18 02:14
#include <iostream>#include <algorithm>using namespace std;typedef struct List* ListPointer;struct node{    int value;    node *next;    void init(int n){        value = n;        next = NULL;    }    void insert(node *&n){        n->next = next;        next = n;    }};struct List{    int length;    node *head;    void init(int n){        length = n;        head = new node();        head->init(0);        node *work = head;        while(n--){            node *t = new node();            t->init(rand()%100);            work->next = t;            work = work->next;        }    }    void insert_sort(){        if(length <= 1)return;        node *now = head->next->next;        for(int i=1; i<=length-1; ++i){            node *store = now;            node *run = head->next;            now = now->next;            store->next = NULL;            for(int j=1; j<=i; ++j){                if(store->value < run->value){                    swap(run->value,store->value);                    break;                }                if(i!=j)run=run->next;            }            run->insert(store);        }    }    void show(){        node *work = head->next;        for(int i=1; i<=length; ++i){            cout << work->value << " ";            work = work->next;        }        cout << endl;    }    ~List(){        node *work = head;        for(int i=0; i<=length; ++i){            node *t = work->next;            free(work);            work = t;        }        head = NULL;        length = 0;    }};int main(){    int n;    ListPointer L;    while(cin >> n){        L = new List();        L->init(n);        L->show();        L->insert_sort();        L->show();        delete L;    }    return 0;}