因为单链表不能按照下表索引访问元素,因此不能够进行远程交换排序、或者动态分治法排序,能想到的只是相邻元素交换的冒泡排序。
代码:
- #include <iostream>
- using namespace std;
- /*
- * 编程实现单链表的排序
- */
- typedef struct Student{
- int data;
- struct Student *next;
- }node;
- //获取单链表的长度
- int lenList(node* head){
- if(head==NULL) return 0;
- node *p = head;
- int sum=0;
- while(p!=NULL){
- sum+=1;
- p=p->next;
- }
- return sum;
- }
- //对单链表排序,因为单链表不能随机访问,只能相邻交换
- void sortList(node* head){
- int len = lenList(head);
- cout<<"len:"<<len<<endl;
- if(len==0) return;
- node *p = head;
- for(int i=1; i<len; ++i){
- //i表示冒泡的次数,共len-1次
- p = head;
- for(int j=0; j<len-i; j++){
- //j表示下落的数目
- if(p->data < p->next->data){
- int tmp = p->data;
- p->data = p->next->data;
- p->next->data = tmp;
- }
- p=p->next;
- }
- }
- }
- void printList(node* head){
- node *p = head;
- cout<<"List:"<<endl;
- while(p!=NULL){
- cout<<p->data<<" ";
- p=p->next;
- }
- cout<<endl;
- }
- void main(){
- int arr[10] = {3,4,9,1,5,2,8,0,6,7};
- node* head = (node*)malloc(sizeof(node));
- head->data = arr[0];
- head->next = NULL;
- node *p = NULL;
- for(int i=1; i<10; ++i){
- p = (node*)malloc(sizeof(node));
- p->data = arr[i];
- p->next = head->next;
- head->next = p;
- }
- printList(head);
- sortList(head);
- printList(head);
- system("pause");
- }
运行结果:
![](http://job.xdnice.com/upload/2012-12/121203161110261.png)
转自:http://www.guolairen.com/bishi/767241.html