Advertisement
ruhan008

Stack implementation program

Nov 8th, 2023 (edited)
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.22 KB | None | 0 0
  1. // 3) WAP to implement Stack
  2. #include <iostream>
  3. using namespace std;
  4. const int StackSpace=4;
  5. int top=-1;
  6. int Stack[StackSpace];
  7.  
  8. void push(int data){
  9.     if(top==(StackSpace-1)){
  10.         cout<<"Stack over flowed!!!"<<endl;
  11.         return ;
  12.     }
  13.     Stack[++top] = data;
  14. }
  15.  
  16. void pop(){
  17.     if(top==-1){
  18.         cout<<"Stack under flowed!!!"<<endl;
  19.         return ;
  20.     }
  21.     top--;
  22. }
  23.  
  24. void peek(){
  25.     if(top==-1){
  26.         cout<<"Stack is empty!!!"<<endl;
  27.         return ;
  28.     }
  29.     cout<<"Current top element of stack: "<<Stack[top]<<endl;
  30. }
  31.  
  32. void size(){
  33.     cout<<"Current stack size: "<<top+1<<endl;
  34. }
  35.  
  36. void printStack(){
  37.     cout<<"Current stack elements:"<<endl;
  38.     for(int i=top;i>=0;i--){
  39.         cout<<Stack[i]<<endl;
  40.     }
  41. }
  42. int main(){
  43.    
  44.  
  45.     push(10);
  46.     push(20);
  47.     push(30);
  48.     push(40);
  49.     peek();
  50.     size();
  51.     printStack();
  52.     pop();
  53.     peek();
  54.     size();
  55.     printStack();
  56.    
  57.     return 0;
  58. }
  59. /*
  60.     OUTPUT:
  61.  
  62.     Current top element of stack: 40
  63.     Current stack size: 4
  64.     Current stack elements:
  65.     40
  66.     30
  67.     20
  68.     10
  69.     Current top element of stack: 30
  70.     Current stack size: 3
  71.     Current stack elements:
  72.     30
  73.     20
  74.     10
  75. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement