VOOZH about

URL: https://www.geeksforgeeks.org/cpp/stack-push-and-pop-in-c-stl/

⇱ stack::push() and stack::pop() in C++ STL - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

stack::push() and stack::pop() in C++ STL

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.

Syntax

st.push(val);

where, st is the name of the stack

Parameters

  • val: Value to be pushed/inserted.

Return Value

  • This function does not return any value.

Managing data with stacks is essential for various applications.

Example of stack::push()


Output
 2 1 0

Time Complexity: O(1)
Auxiliary Space: O(1)

stack::pop()

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.

Syntax

st.pop()

Parameters

  • This function does not take any parameter.

Return value

  • This function does not return any value.

Example of stack::pop()


Output
 2 1

Time Complexity: O(1)
Auxiliary Space: O(1)


Comment