北林oj数据结构295

基于双向链表的双向冒泡排序法

描述

有n个记录存储在带头结点的双向链表中,利用双向冒泡排序法对其按上升序进行排序,请写出这种排序的算法。(注:双向冒泡排序即相邻两趟排序向相反方向冒泡)。

输入

多组数据,每组数据两行。第一行为序列的长度n,第二行为序列的n个元素(元素之间用空格分隔,元素都为正整数)。当n等于0时,输入结束。

输出

每组数据输出一行,为从小到大排序后的序列。每两个元素之间用空格隔开。

输入样例 1 

5
4 5 3 2 9
6
1 3 5 7 9 2
0

输出样例 1

2 3 4 5 9
1 2 3 5 7 9
#include<iostream>
using namespace std;

typedef struct LNode {
	int data;
	struct LNode* next, * front;
}LNode,*LinkList;

void Create(LinkList& L, int n) {
	L = new LNode;
	L->next = NULL;
	L->front = NULL;

	LNode* s, * r = L;
	for (int i = 0; i < n; i++) {
		s = new LNode;
		cin >> s->data;
		s->next = r->next;
		s->front = r;
		r->next = s;
		r = s;
	}
}

void Sort(LinkList &L) {
	LNode* head = L;
	LNode* tail = NULL;
	int flag = 1;
	while (flag) {//向下冒泡
		LNode* p = head->next;//工作指针
		flag = 0;//提前结束
		while (p->next!=tail) {
			if (p->data > p->next->data) {//冒泡交换
				flag = 1;
				LNode* temp = p->next;
				p->next = temp->next;
				if (temp->next != NULL) { temp->next->front = p; }
				p->front->next = temp;
				temp->front = p->front;
				p->front = temp;
				temp->next = p;
			}
			else {
				p = p->next;
			}
		}
		tail = p;
		p = tail->front;
		while (flag && p->front != head) {
			if (p->data < p->front->data) {
				LNode* temp = p->front;
				p->front = temp->front;
				if (temp->front != NULL) { temp->front->next = p; }
				p->next->front = temp;
				temp->next = p->next;
				temp->front = p;
				p->next = temp;
			}
			else {
				p = p->front;
			}
		}
		head = p;
	}

	
}
void Output(LinkList L) {
	LNode* p = L->next;
	while (p) {
		if (p->next != NULL) {
			cout << p->data << " ";
		}
		else {
			cout << p->data;
		}
		p = p->next;
	}
	cout << endl;
}


int main() {
	int n;
	while (cin >> n && n != 0) {
		LinkList L1;
		Create(L1, n);
		Sort(L1);
		Output(L1);
	}
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值