Advertisement
lordasif

link list push front pop front

Mar 19th, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.47 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. struct Node
  4. {
  5. int val;
  6. Node * next;
  7. };
  8.  
  9. struct LinkedList
  10. {
  11. private:
  12. Node * head = NULL;
  13. public:
  14. void push_front(int v)
  15. {
  16. Node node1;
  17. Node * temp = new Node;
  18. (*temp).val = v;/// temp -> val = v; temp -> n
  19. temp->next = NULL;
  20. if (head == NULL)
  21. {
  22. head = temp;
  23. }
  24. else
  25. {
  26. temp->next = head;
  27. head = temp;
  28. }
  29. }
  30. int get_front_element()
  31. {
  32. if (head == NULL)
  33. {
  34. printf("No element\n");
  35. return -1;
  36. }
  37. else
  38. return head->val;
  39. }
  40. void display()
  41. {
  42. if (head == NULL)
  43. printf("No element!\n");
  44. else
  45. {
  46. Node * temp = head;
  47. while (temp != NULL)
  48. {
  49. printf("%d ", temp->val);
  50. temp = temp->next;
  51. }
  52. printf("\n");
  53. }
  54. }
  55. void dispose()
  56. {
  57. Node * temp;
  58. while (head != NULL)
  59. {
  60. temp = head;
  61. head = head->next;
  62. delete temp;
  63. }
  64. printf("All elements are cleared!\n");
  65. }
  66.  
  67. int pop_front()
  68. {
  69. if (head == NULL)
  70. {
  71. printf("Linked List is empty");
  72. return -1;
  73. }
  74.  
  75. else
  76. {
  77. Node * temp = head;
  78. head = temp->next;
  79. int ret = temp->val;
  80. delete temp;
  81. return ret;
  82. }
  83.  
  84.  
  85. }
  86.  
  87. };
  88.  
  89.  
  90. class Stack
  91. {
  92. LinkedList l1;
  93. int n = 0;
  94.  
  95. public:
  96. void push(int v)
  97. {
  98. n++;
  99. l1.push_front(v);
  100. }
  101. int pop()
  102. {
  103. if (n == 0)
  104. {
  105. printf("Stack is empty");
  106. return -1;
  107. }
  108.  
  109. n--;
  110. return l1.pop_front();
  111. }
  112. int size()
  113. {
  114. return n;
  115. }
  116. int peek()
  117. {
  118. return l1.get_front_element();
  119. }
  120. int isEmpty()
  121. {
  122. return !n;
  123. }
  124. void display()
  125. {
  126. l1.display();
  127. }
  128. void dispose()
  129. {
  130. l1.dispose();
  131. }
  132. };
  133.  
  134. int main()
  135. {
  136. Stack s;
  137. s.push(1);
  138. s.push(2);
  139. s.push(3);
  140. s.push(4);
  141. s.push(5);
  142. printf("Stack Top: %d\n", s.peek());
  143. int x = s.pop();
  144. printf("Popped element is : %d\n", x);
  145. printf("Stack Top: %d\n", s.peek());
  146. s.dispose();
  147.  
  148. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement