链表排序

来源:互联网 发布:梦想小镇辅助mac 编辑:程序博客网 时间:2024/05/22 13:18

将一个链表中的元素按照从小到大的顺序进行排序

#include <stdio.h>#include <iostream>using namespace std;//定义结构体类型Ptypedef struct point{int data;struct point *next;//指向结构体的指针}P;//创建链表(指定长度,存在结构体数组中),返回头指针P *createlink(P a[],int n){P *head=&a[0];for(int i=0;i<n-1;i++){a[i].next=&a[i+1];}a[n-1].next=NULL;return head;}//链表输出void output(P *head){P *ph=head;while(ph!=NULL){cout<<ph->data<<'\t';ph=ph->next;}}//链表排序void sortlink(P *head){P *p1=NULL;P *p2=head;bool flag;while(1){p1=NULL;p2=head;flag=false;while(p2){p1=p2;p2=p2->next;if(p2 && p2->data < p1->data){flag=true;int t;t=p2->data;p2->data=p1->data;p1->data=t;}}if(flag==false) break;}}int main(){P a[8]={{10},{1},{12},{15},{6},{9},{4},{0}},*head;head=createlink(a,8);printf("未排序的链表数据如下:\n");output(head);printf("\n====================\n");sortlink(head);printf("排序后的链表数据如下:\n");output(head);cout<<endl;system("pause");return 0;}

输出结果显示:


0 0