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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer Geeks Classes Live