連結串列排序之 氣泡排序
阿新 • • 發佈:2019-02-03
#include <stdio.h> #include <stdlib.h> typedef struct guest { int num; struct guest *next; }guest; guest * Create(); int main() { int i, j, count = 0; guest *h, *p1, *p2, *head; head = Create(); h = head->next; while (h) /* 計算節點數 */ { count++; h = h->next; } for (i = 0; i < count; i++) { h = head; p1 = h->next; p2 = p1->next; for (j = 0; j < count && p2; j++) { if (p1->num > p2->num) { h->next = p2; p1->next = p2->next; p2->next = p1; } h = h->next; p1 = h->next; p2 = p1->next; } } h = head->next; while (h) { printf("%d ", h->num); h = h->next; } return 0; } guest * Create() //建立帶 頭節點 的連結串列 { int i = 0; guest *head, *p1, *p2; head = p1 = p2 = (guest *)malloc(sizeof(guest)); while (i++ < 5) { p1 = (guest*)malloc(sizeof(guest)); scanf("%d", &p1->num); p2->next = p1; p2 = p1; } p2->next = NULL; return head; }
執行結果 :