fork download
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. struct Node{
  5. int data;
  6. Node *next;
  7.  
  8. Node (int d){
  9. data = d;
  10. next = NULL;
  11. }
  12. };
  13.  
  14. struct stack{
  15. Node *top = NULL;
  16. int cnt = 0;
  17.  
  18. void push(int d);
  19. void pop();
  20. int Size();
  21. bool Empty();
  22. int Top();
  23. };
  24.  
  25. void stack::push(int d){
  26. Node *newNode = new Node(d);
  27. if(top == NULL){
  28. top = newNode;
  29. }
  30. else{
  31. newNode->next = top;
  32. top = newNode;
  33. }
  34. cnt++;
  35. }
  36.  
  37. void stack:: pop(){
  38. if(top == NULL){
  39. cout<<"stack is empty. Underflow....\n";
  40. }
  41. else{
  42. Node *del = top;
  43. top = top->next;
  44. delete del;
  45. cnt--;
  46. }
  47. }
  48.  
  49. int stack:: Size(){
  50. return cnt;
  51. }
  52.  
  53. bool stack:: Empty(){
  54. if(Size()== 0){
  55. return 1;
  56. }
  57. return 0;
  58. }
  59.  
  60. int stack:: Top(){
  61. if(top == NULL){
  62. cout<< "stack is empty.\n";
  63. return -1;
  64. }
  65. return top->data;
  66. }
  67.  
  68. int main(){
  69. stack st;
  70.  
  71. st.push(10);
  72. st.push(20);
  73. st.push(30);
  74. st.push(40);
  75. st.push(50);
  76.  
  77. cout<<"Top value: "<<st.Top()<<endl;
  78.  
  79. while(st.Empty() != 1){
  80. cout<< st.Top() <<endl;
  81. st.pop();
  82. }
  83.  
  84. return 0;
  85. }
Success #stdin #stdout 0.01s 5324KB
stdin
Standard input is empty
stdout
Top value: 50
50
40
30
20
10