双向循环链表的冒泡排序
之前和群友水群的时候被认为双向循环链表不能实现冒泡排序,于是实现了一下,哪有什么不能的 ,下面是纯c的代码实现.如果错误还请指正.
#include <stdio.h>
#include <stdlib.h>
int n = 0;//链表中的数据的数量++
struct Two_way_list{
struct Two_way_list* front;
struct Two_way_list* behind;
int val;
};
void Two_way_list_init(struct Two_way_list *head,struct Two_way_list* end){
head = NULL;
end = NULL;
return ;
}
void Two_way_list_insert(struct Two_way_list** head,struct Two_way_list** end,int temp){
if(n == 0){ // 如果是第一次插入数据
*head = (struct Two_way_list *)malloc(sizeof(struct Two_way_list));
*end = *head;
(*head) -> front = head;
(*head) -> behind = head;
(*head)->val = temp;
}
else{
struct Two_way_list* pte = (struct Two_way_list *)malloc(sizeof(struct Two_way_list));
pte -> val = temp;
(*end) -> behind = pte;
pte -> front = *end;
pte -> behind = *head;
(*head) -> front = pte;
*end = pte;
}
++ n;
return ;
}
void Two_way_list_print(struct Two_way_list *head,struct Two_way_list * end){
struct Two_way_list * temp = head;
while(temp != end){
printf("%d ",temp->val);
temp = temp -> behind;
}
printf("%d\n",temp->val);
return ;
}
void Two_way_list_bubble(struct Two_way_list** H,struct Two_way_list** E){
if(n <= 1)
return ;
for(int i = 0;i < n;++ i){
struct Two_way_list *head = *H, * end = *E;
struct Two_way_list * temp = head;
while(temp != end){
if(temp->val > temp->behind->val){
temp -> behind -> front = temp -> front;
temp -> front -> behind = temp ->behind;
temp -> front = temp -> behind;
temp -> behind = temp -> behind -> behind;
temp -> behind -> front = temp;
temp -> front -> behind = temp;
temp = temp -> front;//交换之后temp向后移动了一个位置,所以移动回来
}
if(temp -> behind == head){
head = temp;
*H = temp;
}
if(temp == end){
end = temp -> behind;
*E = temp -> behind;
}
temp = temp -> behind;
}
}
return ;
}
int main(){
struct Two_way_list *head ,*end;
Two_way_list_init(head,end);
int temp = 0;
while(scanf("%d",&temp)!=EOF){
Two_way_list_insert(&head,&end,temp);
}
Two_way_list_bubble(&head, &end);
Two_way_list_print(head,end);
while(scanf("%d\n",&temp)!=EOF){
Two_way_list_insert(&head, &end, temp);
}
Two_way_list_bubble(&head, &end);
Two_way_list_print(head,end);
return 0;
}