Stack in C++


Advertisements

A stack is a linear dynamic data structure that follows Last-In/First-Out (LIFO) principle. In a stack, addition of a new element and deletion of an element occurs at the same end which implies that the element which is added last in the stack will be the first to be removed from the stack.

Features of stack

  • It is a dynamic data structure.
  • It has dynamic size.
  • It uses dynamic memory allocation.

Operations of a stack

  • isEmpty(): Checks whether the stack is empty or not.
  • size(): Returns the size of the stack.
  • topElement(): Returns the top element of the stack.
  • push(x): Adds a new element ‘x’ at the top of the stack. Consequently, size of the stack increases by 1.
  • Stack Push
  • pop(): Deletes the top element of the stack. Consequently, size of the stack decreases by 1.
  • Stack Pop

Implementation of Stack

#include <iostream>
using namespace std;

#define MAX 100 
class CreateStack {
  int top;

  public:
  //assigning MAX size of the stack
  int stack[MAX];

  CreateStack() {
    top = -1;
  }

  void isEmpty();
  int size();
  void push(int x);
  void pop();
  int topElement();
};

  // create a function to check whether 
  // the stack is empty or not  
  void CreateStack::isEmpty() {
    if(top == -1) {
      cout<<"Stack is empty."<<"\n";
    } else {
      cout<<"Stack is not empty."<<"\n";
    }
  }

  //create a function to return size of the stack 
  int CreateStack::size() {
     return top+1;
  } 

  //create a function to add new element       
  void CreateStack::push(int x){
    if(top == (MAX - 1)){
      cout<<"Stack size limit reached."<<"\n";
    } else {
      stack[++top] = x;
      cout<<x<<" is added into the stack."<<"\n";
    }
  }

  //create a function to delete top element       
  void CreateStack::pop(){
    if(top < 0){
      cout<<"Stack is empty."<<"\n";
    } else {
      int x = stack[top--];
      cout<<x<<" is deleted from the stack."<<"\n";
    }
  }  

  //create a function to get top element       
  int CreateStack::topElement() {
    if(top < 0) {
      cout<<"Stack is empty."<<"\n";
      return 0;
    } else {
      return stack[top];
    }
  }


// test stack implementation code 
int main() {
  class CreateStack MyStack;
  MyStack.push(10);
  MyStack.push(20);
  MyStack.push(30);
  MyStack.push(40);

  MyStack.pop();
  MyStack.isEmpty();
  return 0; 
}

Output

10 is added into the stack.
20 is added into the stack.
30 is added into the stack.
40 is added into the stack.
40 is deleted from the stack.
Stack is not empty.
Advertisements