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 *createNode(int data)
  12. {
  13. node *ptr = NULL;
  14. ptr = malloc(sizeof(node));
  15. if(ptr == NULL)
  16. {
  17. printf("space could not be allocated\n");
  18. return NULL;
  19. }
  20.  
  21. ptr->data = data;
  22. ptr->next = NULL;
  23. ptr->prev = NULL;
  24.  
  25. return ptr;
  26. }
  27.  
  28. node *tailInsert(node *head, int data)
  29. {
  30. if(head->next == NULL)
  31. {
  32. node *temp;
  33. temp = createNode(data);
  34. temp->next = NULL;
  35. temp->prev = head;
  36. head->next = temp;
  37. return head;
  38. }
  39. tailInsert(head->next, data);
  40. return head;
  41. }
  42.  
  43. node *frontInsert(node *head, int data)
  44. {
  45. node *newHead;
  46.  
  47. if(head == NULL)
  48. {
  49. return createNode(data);
  50. }
  51.  
  52. newHead = createNode(data);
  53. newHead->next = head;
  54. newHead->prev = NULL;
  55. head->prev = newHead;
  56.  
  57. return newHead;
  58. }
  59.  
  60. node *destroy_linked_list(node *list)
  61. {
  62. /*if (list == NULL)
  63. return NULL;
  64.  
  65. // Free the entire list within this struct.
  66. destroy_list(list->head);
  67.  
  68. // Free the struct itself.
  69. free(list);
  70.  
  71. */
  72. return NULL;
  73. }
  74.  
  75. void printList(node *head)
  76. {
  77. if (head == NULL)
  78. {
  79. printf("Empty List\n");
  80. return;
  81. }
  82.  
  83. for(; head != NULL; head = head->next)
  84. printf("%d ", head->data);
  85.  
  86. printf("\n");
  87. }
  88.  
  89. int main(void)
  90. {
  91. node *head = NULL;
  92.  
  93. head = frontInsert(head, 1);
  94. head = frontInsert(head, 2);
  95. head = frontInsert(head, 3);
  96. head = tailInsert(head, 4);
  97. head = tailInsert(head, 5);
  98. head = tailInsert(head, 6);
  99.  
  100. printList(head);
  101.  
  102. //system("PAUSE");
  103. return 0;
  104. }
Success #stdin #stdout 0s 9424KB
stdin
Standard input is empty
stdout
3 2 1 4 5 6