Wednesday 4 January 2017

Stack Data Structure Implementation using class in Cpp

Stack:-
Stack is a linear data structure which follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out).
Mainly the following three basic operations are performed in the stack:
  • Push: Adds an item in the stack. If the stack is full, then it is said to be an Overflow condition.
  • Pop: Removes an item from the stack. The items are popped in the reversed order in which they are pushed. If the stack is empty, then it is said to be an Underflow condition.
  • Peek: Get the topmost item.

Proram:-

#include <bits/stdc++.h>
using namespace std;
#define Capacity 50  //Capacity of stack;
class Stack{
    int top,capacity;
    int *arr;
    public:
    Stack(int size){
        arr = new int(size);
        top = -1;
        capacity=size;
    }
    bool isEmpty();
    bool isFull();
    void push(int );
    void pop();
    void print();
    int peek();   
};

bool Stack::isEmpty(){
    if(top==-1) {
      cout<<"stack is Empty\n"; 
      return true;
    }
    return false;
}

bool Stack::isFull(){
    if(top==capacity-1){
        cout<<"stack is Full\n";
        return true;
    }
    return false;
}

int Stack::peek(){
    if(isEmpty()) return -1;
    else return arr[top];
}

void Stack::push(int value){
    if(isFull()) return;
    cout<<"push the element "<<value<<endl;
    arr[++top]=value;
}

void Stack::pop(){
    if(isEmpty()) return;
    cout<<"pop element is: ";
    cout<<arr[top--]<<endl;
}

void Stack::print(){
  if(isEmpty()) return ;
  cout<<"stack element are: " <<endl;
  for(int i=0;i<=top;i++) cout<<arr[i]<<" ";
}
int main()
{
    Stack stack(Capacity);
    stack.pop();
    stack.push(1);
    stack.push(6);
    stack.push(4);
    stack.push(2);
    stack.push(7);
    cout<<"Top Element of stack is: "<<stack.peek()<<endl;
    stack.push(8);
    stack.pop();
    stack.print();
    return 0;
}

No comments:

Post a Comment