How to Push an Element into Stack in C++?
Last Updated :
04 Mar, 2024
In C++ Stacks are a type of container adaptor with LIFO(Last In First Out) type of work, where a new element is added at one end (top) and an element is removed from that end only. In this article, we will learn to push the elements onto a Stack in C++.
Example:
Input:
myStack = {40};
Output:
myStack: {40, 30, 20, 10};
Insert Elements in a Stack in C++
To push an element onto a std::stack in C++, we can use the std::stack::push() function, which inserts or pushes the element at the top of the stack. This is the inbuilt function that is provided by the C++ inside the std::stack class template.
C++ Program to Push an Element into a Stack
C++
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack< int > stackData;
stackData.push(10);
stackData.push(20);
stackData.push(30);
stackData.push(40);
cout << "Stack: " ;
while (!stackData.empty()) {
cout << stackData.top();
stackData.pop();
if (!stackData.empty()) {
cout << ", " ;
}
}
cout << endl;
return 0;
}
|
Output
Stack: 40, 30, 20, 10
Time Complexity: O(N), where N is the number of elements to be inserted.
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...