fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4.  
  5. struct Node
  6. {
  7. int value;
  8. struct Node *next;
  9. };
  10.  
  11. typedef struct Node Node;
  12.  
  13.  
  14. Node* sortList(Node* head)
  15. {
  16. Node* newHead = NULL;
  17.  
  18. while (head != NULL)
  19. {
  20. Node *prev = NULL, *cur = newHead, *tmp = head->next;
  21. while (cur && cur->value < head->value)
  22. {
  23. prev = cur;
  24. cur = cur->next;
  25. }
  26. head->next = cur;
  27. if (prev)
  28. prev->next = head;
  29. else
  30. newHead = head;
  31.  
  32. head = tmp;
  33. }
  34.  
  35. return newHead;
  36. }
  37.  
  38.  
  39. void printList(const Node* head)
  40. {
  41. while (head)
  42. {
  43. printf("%d ", head->value);
  44. head = head->next;
  45. }
  46. fputc('\n', stdout);
  47. }
  48.  
  49. void freeList(Node *head)
  50. {
  51. while (head)
  52. {
  53. void *victim = head;
  54. head = head->next;
  55. free(victim);
  56. }
  57. }
  58.  
  59.  
  60. int main()
  61. {
  62. Node* head = NULL, *tmp;
  63.  
  64. srand((unsigned)time(NULL));
  65.  
  66. for (int i=0; i<20; ++i)
  67. {
  68. tmp = malloc(sizeof *tmp);
  69. tmp->value = rand() % 100;
  70. tmp->next = head;
  71. head = tmp;
  72. }
  73.  
  74. printList(head);
  75. head = sortList(head);
  76. printList(head);
  77. freeList(head);
  78. }
Success #stdin #stdout 0s 2288KB
stdin
Standard input is empty
stdout
39 37 12 71 46 98 87 1 83 7 45 15 46 3 83 91 25 80 32 17 
1 3 7 12 15 17 25 32 37 39 45 46 46 71 80 83 83 87 91 98