Coders Packet

Implementation of Stack using C++

By Bharat Pandey

Hello Friends, Today we are going to learn the stack and its implementation in C++ using class.

The stack is a linear data structure based on the Last In First Out rule. In stack, we push items one by one on top of the stack and when we pop an item from a stack we remove items from the top of the stack. 

Operation on the stack:

Push(item): insert an item at top of the stack.

pop(): delete an item from the top of the stack.

In stack push items one after one like the above image then we do pop operation we always pop topmost element.

I think you understand the concept of the stack and what is the operation we do in the stack. let understand how we write code in  c++ to implement a stack.

First, we define data-members and member-function in a class stack.

//capacity of array
const int MAX = 100;
//create a class stack
class stack
{
  //private data memeber
  int top;
  public:
    int arr[MAX]; // maximum size of array
    stack()     // constructor call
    {
      top = -1;
    }
    bool push(int x); // member function
    int  pop();
};

then we define the member function of the class stack.

1. Push Operation:

bool stack:: push(int x)
{
// check stack is already full or not .
if(top >= MAX)
{
cout<<"Stack Overflow"<<endl;
return false;
}
//if the stack is not full push element on the stack.
else
{
top +=1;
arr[top] = x;
cout<<"Item Added Succesfully."<<endl;
return true;
}
}

2: Pop Operation:

int stack:: pop()
{
  //if stack is empty show error message.
  if(top < 0)
  {
    cout<<"Stack Underflow"<<endl;
    return 0;
  }
  // else pop item from stack and decrease top value by 1.
  else
  {
    int x = arr[top];
    top -=1;
    return x;
  }
}

 

Download Complete Code

Comments

No comments yet