fork(1) 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)
  19. {
  20. Node **pp = &newHead, *tmp = head->next;
  21. while (*pp && (*pp)->value < head->value)
  22. pp = &(*pp)->next;
  23.  
  24. head->next = *pp;
  25. *pp = head;
  26. head = tmp;
  27. }
  28.  
  29. return newHead;
  30. }
  31.  
  32.  
  33. void printList(const Node* head)
  34. {
  35. while (head)
  36. {
  37. printf("%d ", head->value);
  38. head = head->next;
  39. }
  40. fputc('\n', stdout);
  41. }
  42.  
  43. void freeList(Node *head)
  44. {
  45. while (head)
  46. {
  47. void *victim = head;
  48. head = head->next;
  49. free(victim);
  50. }
  51. }
  52.  
  53.  
  54. int main()
  55. {
  56. Node* head = NULL, *tmp;
  57.  
  58. srand((unsigned)time(NULL));
  59.  
  60. for (int i=0; i<20; ++i)
  61. {
  62. tmp = malloc(sizeof *tmp);
  63. tmp->value = rand() % 100;
  64. tmp->next = head;
  65. head = tmp;
  66. }
  67.  
  68. printList(head);
  69. head = sortList(head);
  70. printList(head);
  71. freeList(head);
  72. }
Success #stdin #stdout 0s 2244KB
stdin
Standard input is empty
stdout
44 47 26 76 97 42 48 12 40 44 79 8 73 56 72 68 81 81 68 48 
8 12 26 40 42 44 44 47 48 48 56 68 68 72 73 76 79 81 81 97