(C language) linked list sorting---insertion sort

  1 /*
  2  * FILE: sort_link.c
  3  * DATE: 20180306
  4  * ==============
  5 * DESCRIPTION: Linked list insertion sort
  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; // Prepare an empty header node to simplify the code
 21         struct node *p;
 22 int i, len = 10;
 23         p = &a;
 24 srand(time(NULL)); // random number seed
 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; // random number between 0-100
 30         }
 31         p->next = NULL;
 32         display((&a)->next);
 33
 34         struct node b = {0, NULL};
 35         struct node *q, *temp;
 36 // Take out one node at a time from the linked list to be sorted,
 37 // Insert into the appropriate position in the sorted list
 38         p = (&a)->next;
 39         while(p != NULL)
 40         {
 41 temp = p->next; // temporarily save the next node
 42                 q = &b;
 43 while(q->next != NULL) // Traverse the sorted linked list and find a suitable position to insert
 44                 {
 45                         if(p->data < q->next->data)
 46                                 break;
 47                         q = q->next;
 48                 }
 49 // found a suitable position to insert
 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 }

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326700030&siteId=291194637