【LeetCode】使用双向冒泡对双向链表进行排序

#include "stdlib.h"
#include "stdio.h"

typedef struct DoubleList
{//双链表
	int data;
	struct DoubleList* next;
	struct DoubleList* prior;
}DoubleList, * PDoubleList;
PDoubleList create_doubeList_head()
{
	PDoubleList head = (PDoubleList)malloc(sizeof(DoubleList));
	head->next = NULL;
	head->prior = NULL;
	return head;
}
int createDoubleList(PDoubleList L)
{
	PDoubleList p = L;
	int nums;
	scanf_s("%d", &nums);
	while (nums!=-1)
	{
		PDoubleList newNode = new DoubleList;
		newNode->data = nums;
		newNode->next = p->next;
		newNode->prior = p;
		p->next = newNode;
		p = newNode;
		scanf_s("%d", &nums);
	}
	return 0;
}
void Traverse_double(PDoubleList L)
{
	PDoubleList p = L->next;
	while (p)
	{
		printf("%d ->", p->data);
		p = p->next;
	}
}
bool DoubleBubbleSort(PDoubleList L)
{//双向冒泡排序依次比较出最大元素,从最大元素开始向前比较最小的元素
	PDoubleList temp_1 = L,temp_2 =NULL;
	PDoubleList p = temp_1->next;
	bool flag = true;
	while (flag)
	{
		p = temp_1->next;
		while (p->next!=temp_2) //p存在下一个节点可以做比较进入循环
		{

			if (p->data > p->next->data)
			{
				PDoubleList q = p->next;
				if (q->next) //如果q的下个节点不为NULL
				{
					q->next->prior = p;
					p->prior->next = q;
					q->prior = p->prior;
					p->next = q->next;
					p->prior = q;
					q->next = p; //
				}
				else
				{
					p->prior->next = q;
					p->next = q->next;
					q->prior = p->prior;
					q->next = p;
					p->prior = q;
				}
			}
			else
			{
				p = p->next;

			}

		}
		temp_2 = p;
		//此时冒泡到最后结束 //开始向前冒泡 p是最后一个元素
		if (temp_2->prior == temp_1)
		{
			return true;
		}
		PDoubleList r = temp_2->prior;
		while (r->prior != temp_1) //r的前一个元素不超过头部已经排好的最小元素
		{
			if (r->prior->data > r->data)
			{
				PDoubleList q = r->prior;
				r->next->prior = q;
				q->prior->next = r;
				r->prior = q->prior;
				q->next = r->next;
				q->prior = r;
				r->next = q; //
			}
			else
			{
				r = r->prior;
			}
		}
		//判断结束调节
		temp_1 = r;
		if (temp_1->next == temp_2) return true;
	}
}
int main()
{
	PDoubleList head = create_doubeList_head();
	createDoubleList(head);
	DoubleBubbleSort(head);
	Traverse_double(head);
	return 0;
}

实现结果

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值