#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;
}
实现结果