【链表】链表上的冒泡排序
来源:互联网 发布:佛山广电网络营业厅 编辑:程序博客网 时间:2024/06/08 13:52
#include <iostream>#include <algorithm>using namespace std;typedef struct List* ListPointer;struct node{int value;node *next;node *front;void init(int n){ value = n; next = front = NULL;}void deLink(node *&n){ this->next = n; n->front = this;}};struct List{int length;node *head; void init(int n){length = n;head = new node();head->init(0);node *work = head;for(int i=1;i<=n;++i){node *t = new node();t->init(rand()%100);work->deLink(t);work = work->next;}work->deLink(head);}void bubbleSort(){node *stop = NULL;for(int i=1;i<=length;++i){node *work = head->next;for(int j=i;j<=length;++j){if(stop == work)break;if(work->value > work->next->value){swap(work->value,work->next->value);stop = work;}work = work->next;}}}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; } length = 0;head = 0; }};int main(){ int n;ListPointer L; while(cin >> n){ L = new List();L->init(n);L->show();L->bubbleSort();L->show();delete L;} return 0;}