Given q number of queries, you need to perform operations on the stack. Queries are of three types 1, 2, and 3. If the operation is to push (1) then push the elements, if the operations are to pop (2) then pop the element and if it is Top (3), then print the element at the top of the stack (If the stack is empty, print “-1”, without quotes).
Input: Queries = 6 3 1 5 1 6 1 7 2 3 Output: -1 6 The first query is to print top, but since the stack is empty, so we print -1. Next three queries are to push 5, 6, and 7, so we pushed them on a stack. Next query is pop, so we popped 7 from a stack. Final query is to print the top, so 6 is there at the top and thus printed.
Approach: Stack can be used to perform the given operation. If the input for a query is 1, then take another input and push the element into the stack using the push() function. If the input for a query is 2, then pop the element using the pop() function in a stack. If the input for a query is 3, then print the top element using the top() function.
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Stack | Set 3 (Reverse a string using stack)
- Sort a stack using a temporary stack
- Stack Permutations (Check if an array is stack permutation of other)
- stack empty() and stack size() in C++ STL
- Infix to Postfix using different Precedence Values for In-Stack and Out-Stack
- Find maximum in stack in O(1) without using additional stack
- Design a stack that supports getMin() in O(1) time and O(1) extra space
- Design a stack to retrieve original elements and return the minimum element in O(1) time and O(1) space
- Design a stack which can give maximum frequency element
- Design and Implement Special Stack Data Structure | Added Space Optimized Version
- Design a stack with operations on middle element
- Spaghetti Stack
- Implement Stack using Queues
- Iterative Postorder Traversal | Set 2 (Using One Stack)
- Implement a stack using single queue
- Stack in C++ STL
- Stack Class in Java
- Stack | Set 4 (Evaluation of Postfix Expression)
- How to create mergable stack?
- How to implement stack using priority queue or heap?
This article is contributed by Team GeeksforGeeks. 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.