Last Updated : 11 Jan, 2025
The stack::push() and stack::pop() method in stack container is used to insert and delete the element from the top of stack. They are the member functions of std::stack container defined inside <stack> header file. In this article, we will learn how to use stack::push() and stack::pop() methods in C++.
stack::push()The stack::push() function is used to insert or 'push' an element at the top of stack container. This increases the size of stack container by 1.
Syntaxst.push(val);
where, st is the name of the stack
Parameters
Return Value
Managing data with stacks is essential for various applications.
Example of stack::push() C++
// C++ program to show how to use the stack::push()
// method to insert elements in a stack
#include <bits/stdc++.h>
using namespace std;
int main() {
stack<int> st;
// Inserting an element in stack
// with push() method
st.push(0);
// Inserting more elements in the stack
st.push(1);
st.push(2);
// Printing stack
while (!st.empty()) {
cout << ' ' << st.top();
st.pop();
}
return 0;
}
Time Complexity: O(1)
Auxiliary Space: O(1)
The stack::pop() function to remove or 'pop' the element from the top of stack. As we are only inserting and removing from the top, the most recently inserted element will be removed first. This decreases the size of stack container by 1.
Syntaxst.pop()
Parameters
Return value
// C++ program to show how to use the stack::pop()
// method
#include <bits/stdc++.h>
using namespace std;
int main() {
stack<int> st;
st.push(1);
st.push(2);
st.push(3);
st.push(4);
// Deleting 2 element from the top
st.pop();
st.pop();
while (!st.empty()) {
cout << ' ' << st.top();
st.pop();
}
return 0;
}
Time Complexity: O(1)
Auxiliary Space: O(1)
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4