fork download
  1. #include <iostream>
  2. using namespace std;
  3. struct node
  4. {
  5. int data;
  6. node *next;
  7. };
  8. class linked_list
  9. {
  10. private:
  11. node *head,*tail;
  12. public:
  13. linked_list()
  14. {
  15. head = NULL;
  16. tail = NULL;
  17. }
  18.  
  19. node* gethead()
  20. {
  21. return head;
  22. }
  23. void front(int n)
  24. {
  25. node *tmp = new node;
  26. tmp -> data = n;
  27. tmp -> next = head;
  28. head = tmp;
  29. }
  30. void after(node *a, int value)
  31. {
  32. node* p = new node;
  33. p->data = value;
  34. p->next = a->next;
  35. a->next = p;
  36. }
  37. void last(int n)
  38. {
  39. node *tmp = new node;
  40. tmp->data = n;
  41. tmp->next = NULL;
  42. if(head == NULL)
  43. {
  44. head = tmp;
  45. tail = tmp;
  46. }
  47. else
  48. {
  49. tail->next = tmp;
  50. tail = tail->next;
  51. }
  52. }
  53. void display_loop()
  54. {
  55. node *tmp;
  56. tmp = head;
  57. while (tmp != NULL)
  58. {
  59. cout << tmp->data << endl;
  60. tmp = tmp->next;
  61. }
  62. cout << "NULL\n\n" << endl;
  63. }
  64. static void display_rec(node *head)
  65. {
  66. if(head == NULL)
  67. {
  68. cout << "NULL\n\n" << endl;
  69. }
  70. else
  71. {
  72. cout << head->data << endl;
  73. display_rec(head->next);
  74. }
  75. }
  76. void del (node *before_del)
  77. {
  78. node* temp;
  79. temp = before_del->next;
  80. before_del->next = temp->next;
  81. delete temp;
  82. }
  83. void del_first()
  84. {
  85. if (head)
  86. {
  87. node* temp = head;
  88. head = head->next;
  89. delete temp;
  90. }
  91. }
  92. void del_last()
  93. {
  94. node* prev;
  95. node* curr;
  96. if (head==NULL)
  97. {
  98. // empty list
  99. }
  100. else if (head->next==NULL)
  101. {
  102. curr = head;
  103. head = NULL;
  104. delete curr;
  105.  
  106. }
  107. else
  108. {
  109. curr = head;
  110. while(curr->next != NULL)
  111. {
  112. prev = curr;
  113. curr = curr->next;
  114. }
  115. prev->next = NULL;
  116. delete curr;
  117. }
  118. }
  119. };
  120. int main()
  121. {
  122. linked_list a;
  123. a.last(1);
  124. a.last(2);
  125. a.front(3);
  126. a.display_loop();
  127.  
  128. linked_list::display_rec(a.gethead());
  129. a.del_last();
  130. linked_list::display_rec(a.gethead());
  131. a.del_first();
  132. a.display_loop();
  133. linked_list::display_rec(a.gethead());
  134. a.del_first();
  135. linked_list::display_rec(a.gethead());
  136. return 0;
  137. }
Success #stdin #stdout 0s 4388KB
stdin
Standard input is empty
stdout
3
1
2
NULL


3
1
2
NULL


3
1
NULL


1
NULL


1
NULL


NULL