双连表冒泡排序

#include "iostream"
using namespace std;
typedef struct da    //定义结构
{
 int num;
 struct da *prior;
 struct da *next;
}data;

data * creatlink()     //形成双连表
{
 data *head ,*tail;
 head = new data;
 tail = head;
 tail ->prior = NULL;
 tail ->next = NULL;
 int nu = 0,i = 0;
 cout<<"输入数字(以-1结束):";
 data *ne;
 while(nu != -1)
 {
   ne = new data;
   cin>>nu;
   ne ->num = nu;
   if(i == 0)     //判断第一次就一个开始节点
   {
        
    tail ->next = ne;
    ne ->prior = tail;

    ne ->next = NULL;
    i = 1;
   }
   else       //其他次插在两节点中间
   {
   
    ne ->prior = head;
    ne ->next = tail ->next;
    tail ->next ->prior = ne;
    tail ->next = ne;

   }
  }
 return tail;   //返回头结点
}

void put(data *head)    //输出双连表内容

 data *temp = head ->next;
 while(temp  != NULL)
 {
  cout<<temp ->num<<' '; 
  temp = temp ->next;

 }
}


void order(data *head)     //冒泡排序功能函数
{
 data *temp1,*temp2,*a,*b;
 int i = 0;
 a = head;
 while(a ->next != NULL)
 {
  temp1 = temp2 = a ->next;
  while(temp1 ->next != NULL)
  {
   temp1 = temp1 ->next;
   if(temp1 ->num >= temp2 ->num)    //找到最大值
    temp2 = temp1;
  }
  for(b = a;b ->next != temp2;b = b ->next);  //找到temp2的前一节点
  b ->next = temp2 ->next;
  if(temp2 ->next != NULL)          //判断temp2是否为尾节点
   temp2 ->next->prior = b;

  head ->next ->prior = temp2;   //将temp2插入head 的后面
  temp2 ->next = head ->next;
  head ->next = temp2;
  temp2 ->prior = head;
  if(i == 0)
  {
   a = temp2;     //将挡板一次赋值
   i = 1;
  }
 }
}
int main(void)
{
 data *head ;
 head = creatlink();  //形成双连表调用
 cout<<"正常输出:";
 put(head);   //输出调用
 cout<<'/n';
 cout<<"排序后输出:";
 order(head);    //排序双连表
 put(head);     //输出双连表
 cout<<'/n';
 getchar();
 getchar();
 getchar();
 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值