fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct Node
  5. {
  6. int data;
  7. struct Node *next;
  8. struct Node *prev;
  9. } Node;
  10.  
  11. Node* SortedInsert(Node *head,int data)
  12. {
  13. Node *p = malloc(sizeof(*p)), **pp = &head;
  14. p->data = data;
  15. p->prev = NULL;
  16.  
  17. while (*pp && (*pp)->data < data)
  18. {
  19. p->prev = *pp;
  20. pp = &(*pp)->next;
  21. }
  22.  
  23. // whatever *pp is, its our next pointer
  24. p->next = *pp;
  25. if (*pp)
  26. (*pp)->prev = p;
  27.  
  28. // this is always set to the new node
  29. *pp = p;
  30. return head;
  31. }
  32.  
  33. void print_list(const Node *head)
  34. {
  35. while (head)
  36. {
  37. printf("%d(", head->data);
  38.  
  39. if (head->prev)
  40. printf("%d,", head->prev->data);
  41. else
  42. printf("null,");
  43.  
  44. if (head->next)
  45. printf("%d) ", head->next->data);
  46. else
  47. printf("null) ");
  48.  
  49. head = head->next;
  50. }
  51. printf("\n");
  52. }
  53.  
  54. void free_list(Node* head)
  55. {
  56. while (head)
  57. {
  58. Node *tmp = head;
  59. head = head->next;
  60. free(tmp);
  61. }
  62. }
  63.  
  64. int main()
  65. {
  66. int ar[] = { 3,1,5,4,6,8,7,9,2 }, i;
  67. Node *head = NULL;
  68.  
  69. // ordered insertion
  70. for (i=1; i<=9; ++i)
  71. head = SortedInsert(head, i);
  72.  
  73. print_list(head);
  74. free_list(head);
  75. head = NULL;
  76.  
  77. // reverse insertion
  78. for (i=9; i>=1; --i)
  79. head = SortedInsert(head, i);
  80.  
  81. print_list(head);
  82. free_list(head);
  83. head = NULL;
  84.  
  85. // unordered insertion
  86. for (i=0; i<sizeof(ar)/sizeof(*ar); ++i)
  87. head = SortedInsert(head, ar[i]);
  88.  
  89. print_list(head);
  90. free_list(head);
  91. head = NULL;
  92.  
  93. return 0;
  94. }
Success #stdin #stdout 0s 2424KB
stdin
Standard input is empty
stdout
1(null,2) 2(1,3) 3(2,4) 4(3,5) 5(4,6) 6(5,7) 7(6,8) 8(7,9) 9(8,null) 
1(null,2) 2(1,3) 3(2,4) 4(3,5) 5(4,6) 6(5,7) 7(6,8) 8(7,9) 9(8,null) 
1(null,2) 2(1,3) 3(2,4) 4(3,5) 5(4,6) 6(5,7) 7(6,8) 8(7,9) 9(8,null)