Stacks are a type of container adaptors with LIFO(Last In First Out) type of working, where a new element is added at one end and (top) an element is removed from that end only.
push() function is used to insert an element at the top of the stack. The element is added to the stack container and the size of the stack is increased by 1.
stackname.push(value) Parameters : The value of the element to be inserted is passed as the parameter. Result : Adds an element of value same as that of the parameter passed at the top of the stack.
Input : mystack mystack.push(6); Output : 6 Input : mystack mystack.push(0); mystack.push(1); Output : 0, 1
Errors and Exceptions
1. Shows error if the value passed doesn’t match the stack type.
2. Shows no exception throw guarantee if the parameter doesn’t throw any exception.
2 1 0 Note that output is printed on the basis of LIFO property
pop() function is used to remove an element from the top of the stack(newest element in the stack). The element is removed to the stack container and the size of the stack is decreased by 1.
stackname.pop() Parameters : No parameters are passed. Result : Removes the newest element in the stack or basically the top element.
Input : mystack = 0, 1, 2 mystack.pop(); Output : 0, 1 Input : mystack = 0, 1, 2, 3, 4, 5 mystack.pop(); Output : 0, 1, 2, 3, 4
Errors and Exceptions
1. Shows error if a parameter is passed.
2. Shows no exception throw guarantee.
2 1 Note that output is printed on the basis of LIFO property
Given a number of integers, add them to the stack and find the size of the stack without using size function.
Input : 5, 13, 0, 9, 4 Output: 5
1. Push the given elements to the stack container one by one.
2. Keep popping the elements of stack until it becomes empty, and increment the counter variable.
3. Print the counter variable.
- stack empty() and stack size() in C++ STL
- Sort a stack using a temporary stack
- priority_queue::push() and priority_queue::pop() in C++ STL
- queue::push() and queue::pop() in C++ STL
- stack top() in C++ STL
- Stack in C++ STL
- stack swap() in C++ STL
- Stack Unwinding in C++
- stack emplace() in C++ STL
- Sort a stack using recursion
- Sudo Placement[1.3] | Stack Design
- Delete middle element of a stack
- Check if the elements of stack are pairwise sorted
- Level order traversal in spiral form | Using one stack and one queue
- Design a stack that supports getMin() in O(1) time and O(1) extra space
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.