In the previous post, we have discussed the C++ implementation of the stack data structure using classes. In this article, we will make code generic for all data types by using C++ templates.

 
The stack can be implemented as follows using templates in C++:

Download  Run Code


Output:
 
Inserting A
Inserting B
Removing B
Removing A
Inserting C
The top element is C
The stack size is 1
Removing C
The stack is empty

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

 
Also See:

Stack Implementation in C

Stack Implementation in C++

Stack Implementation in Java

Stack Implementation in Python

Stack Implementation using a Linked List – C, Java, and Python