首先,我们需要创建一个单链表
#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;
}