单向链表建立 排序

#include<iostream>
using namespace std;  

struct linknote
{
 int date;
 linknote * next;
};
linknote * creatlink()//创建链表
{
 int a;
 char q;
 linknote * head,* m;
 cout<<"input the date one by one divide by space"<<endl;
 head=NULL;
 q='y';
 while(q=='y')
 {
  cin>>a;
  m=head;
  head=new linknote;
  head->next=m;
  head->date=a;
  cout<<"input y or n to decide if go on creat"<<endl;
  cin>>q;
 }
 return head;
}
linknote * findfather(linknote * head2,linknote * current)//找到某个结点的父结点
{
 linknote * temp;
 temp=head2;
 while(temp!=NULL)
 {
  if(temp->next==current)
   return temp;
  temp=temp->next;
 }
}
linknote * change(linknote * head1,linknote * n1,linknote *n2)//交换链表接点的位置
{
 if(head1==NULL)
 {
  cout<<"错误  交换链表为空"<<endl;
  
 }
 if(n1==NULL)
 {
  cout<<"错误 n1 为空"<<endl;
  
 }
 if(n2==NULL)
 {
  cout<<"错误 n2 为空"<<endl;
  
 }
 linknote *m, * temp,*father1,*father2,*baby1,*baby2;
 
 if(n2->next==n1)//保证如果m1,m2 相邻让m1在m2 前面
 {
  temp=n1;
  n1=n2;
  n2=temp;
  m=change(head1,n1,n2);
  return m;
 }
 if(n1!=head1)
  father1=findfather(head1,n1);
 if(n2!=head1)
  father2=findfather(head1,n2);
 baby1=n1->next;
 baby2=n2->next;
 if(n1->next==n2)
 {
  
   n1->next=n2->next;
   n2->next=n1;
   if(n1!=head1)
    father1->next=n2;
   if(n1==head1)
    return n2;
   return head1;
 }
 else
 {
  n1->next=baby2;
  n2->next=baby1;
  if(n1!=head1)
   father1->next=n2;
  if(n2!=head1)
   father2->next=n1;
  if(n1==head1)
   return n2;
  if(n2==head1)
   return n1;
  return head1;
 }
}
linknote * paixu(linknote * head)//给链表排序 用冒泡排序法 从小到大
{
 linknote * m1,*m2;
 m1=NULL;
 m2=NULL;
 int v;
 v=1; 
 while(v==1)  //冒泡循环
 {
  v=0;
  m1=head;
  while(m1!=NULL)
  {
   m2=m1->next;
   
   if(m2!=NULL)
   {
    if((m1->date)>(m2->date))
    {
     head=change(head,m1,m2);
     v=1;
    }
   }
   m1=m1->next;
   m2=NULL;
  }
 }
 return head;
}

void output(linknote * head)
{
 while(head!=NULL)
 {
  cout<<head->date<<" ";
  head=head->next;
 }
 cout<<endl;
}
linknote * insert(linknote * head,int d)//插入用户想插入的数
{
 linknote *q;
 q=head;
 head=new linknote;
 head->date=d;
 head->next=q;
 return head;

}
int main()
{
 int a;
 linknote * head;
 head=creatlink();
 cout<<"排序前"<<endl;
 output(head);
 head=paixu(head);
 cout<<"排序后"<<endl;
 output(head);
 cout<<"input the date you want to input  in "<<endl;
 cin>>a;
 head=insert(head,a);
 head=paixu(head);
 output(head);
 return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值