(C语言)链表排序 --- 插入排序

  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 }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章