用C语言对单链表进行冒泡排序

首先,我们需要创建一个单链表

#include<stdio.h>
#include<malloc.h>
typedef struct cell{
	int x;
	struct cell* next;
}cell;
cell* build(void){
	cell* head, * tmp, * p;
	head = tmp = p = NULL;
	int n;
	scanf("%d", &n);
	if (n == 0) {
		return NULL;
	}
	head = (cell*)malloc(sizeof(cell));
	head->x = n;
	p = head;
	while (1) {
		scanf("%d", &n);
		if (n == 0)
			break;
		tmp = (cell*)malloc(sizeof(cell));
		tmp->x = n;
		p->next = tmp;
		p = tmp;
		p->next = NULL;
	}
	return head;
}
void print(cell* head) {
	cell* s;
	s = head;
	while (s != NULL) {
		printf("%d ", s->x);
		s = s->next;
	}
}
void release(cell* head) {
	cell* p;
	while (head != NULL) {
		p = head;
		head = p->next;
		free(p);
	}
}
int main(void) {
	cell* head;
	head = build();
	if (head != NULL) {
		print(head);
	}
	else
		printf("NULL");
	release(head);
	return 0;
}

接着,我们需要编写冒泡排序所用函数。

cell* sort(cell* head) {
	cell* i, *j;
	int temp = 0;
	for (i = head; i != NULL; i = i->next) {
		for (j = head; j->next != NULL; j = j->next) {
			if (j->x > j->next->x) {
				temp = j->next->x;
				j->next->x = j->x;
				j->x = temp;
			}
		}
	}
	return head;
}

最终:

#include<stdio.h>
#include<malloc.h>
typedef struct cell{
	int x;
	struct cell* next;
}cell;
cell* build(void){
	cell* head, * tmp, * p;
	head = tmp = p = NULL;
	int n;
	scanf("%d", &n);
	if (n == 0) {
		return NULL;
	}
	head = (cell*)malloc(sizeof(cell));
	head->x = n;
	p = head;
	while (1) {
		scanf("%d", &n);
		if (n == 0)
			break;
		tmp = (cell*)malloc(sizeof(cell));
		tmp->x = n;
		p->next = tmp;
		p = tmp;
		p->next = NULL;
	}
	return head;
}
cell* sort(cell* head) {
	cell* i, *j;
	int temp = 0;
	for (i = head; i != NULL; i = i->next) {
		for (j = head; j->next != NULL; j = j->next) {
			if (j->x > j->next->x) {
				temp = j->next->x;
				j->next->x = j->x;
				j->x = temp;
			}
		}
	}
	return head;
}
void print(cell* head) {
	cell* s;
	s = head;
	while (s != NULL) {
		printf("%d ", s->x);
		s = s->next;
	}
}
void release(cell* head) {
	cell* p;
	while (head != NULL) {
		p = head;
		head = p->next;
		free(p);
	}
}
int main(void) {
	cell* head, *ptr;
	ptr = build();
	head = sort(ptr);
	if (head != NULL) {
		print(head);
	}
	else
		printf("NULL");
	release(head);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值