双向循环链表的冒泡排序

双向循环链表的冒泡排序

之前和群友水群的时候被认为双向循环链表不能实现冒泡排序,于是实现了一下,哪有什么不能的 ,下面是纯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;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值