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


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.


Download   Run Code


Download   Run Code


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

Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of