C++ 链表冒泡法排序算法
//linked list bubble sort //programming by : Erfan Nasoori //Mail : ketn68@yahoo.com //Date of send : 2009/1/13 #include <iostream> #include <conio> class node { friend class linklist; int number; node *next; }; class linklist { private: node *first; node *last; public: linklist(){ first = NULL; } ~linklist(){}; void addnode(); void BubbleSort(); void displaynode(); }; void linklist :: addnode() { node *newno; do { newno = new node; newno->next=NULL; cout<<"Number : "; cin>>newno->number; if(first==NULL) first=last=newno; else { last->next=newno; last=newno; } }while(newno->number != 0); } void linklist :: displaynode() { cout<<"---------------------\nSorted numbers :\n"; node *curno=first; while(curno) { cout<<curno->number<<' '; curno=curno->next; } } void linklist ::BubbleSort() { int i,j,m,n=0,hold; node *q, *p, *t; for(node*q = first ; q ; q=q->next) //balad shodid; ++n; for(i=1 , t = first ; i<=n-1 ; t = t->next , ++i) for( j=0 , p = first ; j<n-i ; p = p->next , ++j) if(p->number > (p->next)->number) { hold = p->number; p->number = (p->next)->number; (p->next)->number = hold; } } void main() { linklist sl; sl.addnode(); sl.BubbleSort(); sl.displaynode(); getch(); }