【链表】链表上的选择排序

来源:互联网 发布:佛山广电网络营业厅 编辑:程序博客网 时间:2024/05/17 20:41
#include <iostream>#include <algorithm>using namespace std;struct node{    int v;    node *next;    void init(int n){        v = n;        next = NULL;    }};struct List{    int length;    node *head;    void init(int l){        length = l;        head = new node();        head->init(0);    }    ~List(){        node *work = head;        for(int i=1; i<=length; ++i){            node *t = work->next;            delete work;            work = t;        }        length = 0;        head = NULL;    }};void creat(List *&L,int n){    int num;    node *tail = L->head;    while(n--){        node *t = new node();        t->init(rand()%100);        tail->next = t;        tail = tail->next;    }    tail->next = L->head;}void List_sort(List *&L){    node *store = NULL;    node *first = L->head->next;    for(int i=1; i<=L->length; ++i){        node *work = first;        int max = first->v;        store = first;        for(int j=i+1; j<=L->length; ++j){            work = work->next;            if(work->v > max){                max = work->v;                store = work;            }        }        swap(first->v,store->v);        first = first->next;    }}void show(List *L){    node *work = L->head->next;    for(int i=1;i<=L->length;++i){        cout << work->v << " ";        work = work->next;    }    cout << endl;}int main(){    int n;    List *L;    while(cin >> n){        L = new List();        L->init(n);        creat(L,n);        show(L);        List_sort(L);        show(L);        delete L;    }    return 0;}