1 /* 2 * FILE: sort_link.c 3 * DATE: 20180306 4 * ============== 5 * DESCRIPTION: 鏈表插入排序 6 */ 7 8 #include <stdio.h> 9 #include <stdlib.h> 10 11 struct node{ 12 int data; 13 struct node *next; 14 }; 15 16 void display(struct node *); 17 18 int main(int argc, char *argv[]) 19 { 20 struct node a; // 准備一個空的頭節點,可簡化代碼 21 struct node *p; 22 int i, len = 10; 23 p = &a; 24 srand(time(NULL)); // 隨機數種子 25 for(i=0; i<len; i++) 26 { 27 p->next = (struct node *)malloc(sizeof(struct node)); 28 p = p->next; 29 p->data = rand() % 100; // 0-100間的隨機數 30 } 31 p->next = NULL; 32 display((&a)->next); 33 34 struct node b = {0, NULL}; 35 struct node *q, *temp; 36 // 待排序鏈表中每次取出一個節點, 37 // 插入進已排好序鏈表的合適位置 38 p = (&a)->next; 39 while(p != NULL) 40 { 41 temp = p->next; // 臨時保存下一個節點 42 q = &b; 43 while(q->next != NULL) // 遍歷已排好序的鏈表,尋找合適的位置插入 44 { 45 if(p->data < q->next->data) 46 break; 47 q = q->next; 48 } 49 // 已找到合適位置插入 50 p->next = q->next; 51 q->next = p; 52 p = temp; 53 } 54 55 display((&b)->next); 56 //display((&a)->next); 57 return 0; 58 } 59 60 void display(struct node *head) 61 { 62 struct node *p = head; 63 while(p != NULL) 64 { 65 printf("%d ", p->data); 66 p = p->next; 67 } 68 printf("\n"); 69 }
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。