Stack Implementation in C++

A stack is a linear data structure that serves as a container of objects that are inserted and removed according to the LIFO (last-in first-out) rule.


 

Stack has three main operations: push, pop and peek. We have discussed about these operations in previous post and covered array and linked list implementation of stack data structure in C. In this article, stack implementation in C++ is covered using class.

 
Below stack implementation in C++ covers below operation –
 

  1. push: Inserts a new element at the top of the stack, above its current top element.
     
  2. pop: Removes the top element on the stack, thereby decrementing its size by one.
     
  3. isEmpty: Returns true if stack is empty i.e. its size is zero else it returns false.
     
  4. isFull: Returns true if stack is full i.e. its size has reached maximum allocated capacity else it returns false.
     
  5. peek: Returns the top element present in the stack without modifying the stack.
     
  6. size: Returns the count of elements present in the stack.
     

 

Download   Run Code

Output:

Inserting 1
Inserting 2
Removing 2
Removing 1
Inserting 3
Top element is: 3
Stack size is 1
Removing 3
Stack Is Empty

 

The time complexity of all stack operations is constant. i.e. O(1).

 


 

Several of the C++ Standard Library container types have push_back and pop_back operations with LIFO semantics like std::stack, std::list. Stack is also included in Java’s collection framework.

std::stack

Download   Run Code

std::list

Download   Run Code


Output:

Top element is: D
Stack size is 2
Stack is not Empty

 
1 Star2 Stars3 Stars4 Stars5 Stars (3 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
newest oldest most voted
Notify of
Recep
Guest

it was very helpful for me. ThankU

Amey
Guest

How to delete the stack?