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++ Program to push an elements onto a stack #include <iostream> #include <stack> using namespace std;
// Driver Code int main()
{ // Creating empty Stack
stack< int > stackData;
// Pushing elements to the stack
stackData.push(10);
stackData.push(20);
stackData.push(30);
stackData.push(40);
// Printing the updated stack
cout << "Stack: " ;
while (!stackData.empty()) {
cout << stackData.top();
stackData.pop();
if (!stackData.empty()) {
cout << ", " ;
}
}
cout << endl;
return 0;
} |
Stack: 40, 30, 20, 10
Time Complexity: O(N), where N is the number of elements to be inserted.
Auxiliary Space: O(N)