单链表的冒泡排序

 #include<iostream>//建立链表,进行排序,零时完成,运用了C++的输入与输出 - -! 2009.03.11
#define NULL 0
using std::cout;
using std::cin;
using std::endl;
struct NODE{
 int data;
 NODE *next;
};
void creat_list(NODE *&head,int length);
void selete_range_list(NODE *);
void show_list(NODE *);
void main()
{
 NODE *head;
 int length;
 if((head=new NODE)==NULL) exit(1);//为链表头分配空间,实现head指向的data储存该链表的长度
 do
 {
  cout<<"/ninput the length of the node<1-10>";
  cin>>length;
 }
 while(length<1||length>10);//规定链表的长度范围
 creat_list(head,length);
 show_list(head);//建立并打印初始链表
 cout<<endl;
 selete_range_list(head);
 show_list(head);//冒泡排序后打印链表
 delete []head;//释放空间,疑问每个结点怎么删除
}
void creat_list(NODE *&head,int length)
{
 NODE *then,*first;
 head->data=length;//将链表长度分配给链表头的data中
 if((first=new NODE)==NULL) exit(1);
 head->next=first;
 while(--length>=0)//个人认为学C这么久我写的最精华的语句
 {
  then=new NODE;
  then->next=NULL;
  cin>>then->data;
  first->next=then;
  first=then;
 }
}
void selete_range_list(NODE *head)//所谓的选择排序部分- -!  
{
 NODE *first,*then;
 int *rary,length,n,t,m;
 length=head->data;
 if (head==NULL) exit(1);
 first=head->next;
 if((rary=new int[length])==NULL) exit(1);//建立动态数组,零时储存链表内数据,为排序做准备
 first=head->next;
 for(n=0;n<length;n++)//向动态数组内移入链表数据
 {
  then=first->next;
  rary[n]=then->data;
  first=then;
 }
 for(n=0;n<length-1;n++)//对动态数组内的数据进行傻瓜式的排序,,,- -!
  for(m=n+1;m<length;m++)
   if(rary[n]>rary[m]) {
    t=rary[n];
    rary[n]=rary[m];
    rary[m]=t;
   }
   first=head->next;//将动态数组内排序完成的数据移入链表中
   for(n=0;n<length;n++)
   {
    then=first->next;
    then->data=rary[n];
    first=then;
   }
   delete []rary;//释放动态数组空间

}
void show_list(NODE *head)//打印数组内容
{
 NODE *first;
 first=head->next;
 while(first->next!=NULL)
 {
  first=first->next;
  cout<<first->data<<" ";
 }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值