Stack Using Array In Data Structure Using C++

Data Structure Using C++

Stack Data Structure

Stack Using Array

class stack
{
 private:
  int *ptr;
  int size;
  int current;
 public:
  stack(int l);
  void push (int val);
  int pop ();
  int top ();
  int isFull ();
  int isEmpty();
};
stack::stack(int l)
{
 ptr=new int [l];
 current=-1;
 size=l;
}
void stack::push(int val)
{
 if(!isFull()){
  ptr[++current]=val;  
 }else{
  cout<<"Stack is Full!"<<endl;
 }
}
int stack::pop ()
{
 if(!isEmpty()){
  return ptr[current--];
 }else{
  cout<<"Stack is Empty!"<<endl;
 }
}
int stack::top ()
{
 return ptr[current];
}
int stack::isFull()
{
 return current==--size;
}
int stack::isEmpty()
{
 return current==-1;
}
int main ()
{
 stack s(10);
 if(!s.isFull())
 {
  s.push(4);
 }
 s.push(6);
 s.push(3);
 if(!s.isEmpty())
 {
  cout<<"Popped element is : "<<s.pop();
 }
 cout<<endl<<"top element is : "<<s.top();
}

Let me know in the comment section if you have any question.

Previous Post:
Josephus Problem Using Singly Circular Linked List in Data Structure Using C++

Comments