#include <stdio.h> #include <stdlib.h> #include <time.h> #define N 10 typedef struct node *link; struct node { int item; link next; }; link NODE(int item, link next) { link t = malloc(sizeof *t); t->item = item; t->next = next; return t; } link head; link init_list() { return NODE(-1, NULL); } void show_list(link head) { link t; for(t = head->next; t; t=t->next) printf("%3d", t->item); printf("/n"); } void append_node(link head, int item) { link t; for (t = head; t->next; t = t->next) NULL; t->next = NODE(item, NULL); } void bubble_sort(link head) { link p, x, y, f = NULL; if(head->next == NULL) return; while (f != head->next->next) { for (p = head; p->next->next != f; p = p->next) { if(p->next->item > p->next->next->item) { x = p->next; y = x->next; p->next = y; x->next = y->next; y->next = x; } } f = p->next; } } int main(void) { int i; srand(time(NULL)); head = init_list(); for (i = 0; i < N; i++) append_node(head, rand()%100); show_list(head); bubble_sort(head); show_list(head); return 0; }