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.

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

 
Following is the stack implementation in C++ which covers the following operations:

  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 the stack is empty, i.e., its size is zero; otherwise, it returns false.
  4. isFull: Returns true if the stack is full, i.e., its size has reached maximum allocated capacity; otherwise, 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.

Practice this problem

Stack Implementation using an array:

Download  Run Code


Output:
 
Inserting 1
Inserting 2
Removing 2
Removing 1
Inserting 3
The top element is 3
The stack size is 1
Removing 3
The stack is empty

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

Using STL:

Several of the C++ Standard Library container types have push_back and pop_back operations with LIFO semantics like std::stack, std::list.

std::stack


Download  Run Code

std::list


Download  Run Code

Output:
 
The top element is D
The stack size is 2
The stack is not empty

 
Also See:

Stack Implementation in Java

Stack Implementation in Python