In this post we are going to write C++ program to implement stack data structure using Templates in C++.
Stack is an abstract data type which serves as a collection of elements, with two principal operations i.e. push() and pop(). It works based on LIFO operations also known as “last in, first out”.
![Logitech M510 Wireless Computer Mouse](https://cdn.mycplus.com/mycplus/wp-content/uploads/2025/01/Logitech-M510-Wireless-Computer-Mouse.jpg)
Boost productivity with the Logitech MX Master 3 – the ultimate wireless mouse with ergonomic design, seamless control, and customizable features!
View on Amazon
Initially, the constructor sets the stack contents to NULL and top position to -1 to indicate that the stack is empty.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | #include <dos.h> // for sleep() #include <iostream.h> // for I/0 #include <windows.h> // for MessageBox() API #include <conio.h> #define MAX 10 // MAXIMUM STACK CONTENT template <class T> // Using Templates so that any type of data can be // stored in Stack without multiple defination of class class stack { protected: T arr[MAX]; // Contains all the Data public: T item, r; int top; //Contains location of Topmost Data pushed onto Stack stack() //Constructor { for (int i = 0; i < max; i++) { arr[i] = NULL; //Initializes all Stack Contents to NULL } top = -1; //Sets the Top Location to -1 indicating an empty stack } void push(T a) // Push ie. Add Value Function { top++; // increment to by 1 if (top < max) { arr[top] = a; //If Stack is Vacant store Value in Array } else // Bug the User { MessageBox(0, "STACK IS FULL", "STACK WARNING!", MB_ICONSTOP); top--; } } T pop() // Delete Item. Returns the deleted item { if (top == -1) { MessageBox(0, "STACK IS EMPTY\n", "WARNING", MB_ICONSTOP); return NULL; } else { T data = arr[top]; //Set Topmost Value in data arr[top] = NULL; //Set Original Location to NULL top--; // Decrement top by 1 return data; // return deleted item } } }; void main() { stack<int> a; // Create object of class a with int Template int opt = 1; while (opt != 3) { clrscr(); cout << " MAX STACK CAPACITY=" << ((MAX - a.top) - 1) << "\n\n\n\n"; cout << "1) Push Item\n"; cout << "2) Pop Item\n"; cout << "3) Exit\n\n"; cout << "Option?"; cin >> opt; switch (opt) { case 1: cout << "Which Number should be pushed?"; cin >> a.item; a.push(a.item); break; case 2: a.r = a.pop(); cout << "Item popped from Stack is:" << a.r << endl; sleep(2); break; } } } |