Design a stack with the following operations.
a) push(Stack s, x): Adds an item x to stack s
b) pop(Stack s): Removes the top item from stack s
c) merge(Stack s1, Stack s2): Merge contents of s2 into s1.
Time Complexity of all above operations should be O(1).
If we use array implementation of the stack, then merge is not possible to do in O(1) time as we have to do following steps.
a) Delete old arrays.
b) Create a new array for s1 with a size equal to the size of the old array for s1 plus size of s2.
c) Copy old contents of s1 and s2 to new array for s1
The above operations take O(n) time.
We can use a linked list with two pointers, one pointer to the first node (also used as a top when elements are added and removed from the beginning). The other pointer is needed for the last node so that we can quickly link the linked list of s2 at the end of s1. Following are all operations.
a) push(): Adds the new item at the beginning of linked list using the first pointer.
b) pop(): Removes an item from the beginning using the first pointer.
c) merge(): Links the first pointer second stack as next of the last pointer of the first list.
Can we do it if we are not allowed to use an extra pointer?
We can do it with a circular linked list. The idea is to keep track of the last node in the linked list. The next of the last node indicates the top of the stack.
a) push(): Adds the new item as next of the last node.
b) pop(): Removes next of last node.
c) merge(): Links the top (next of last) of the second list to the top (next of last) of the first list. And makes last of the second list as last of the whole list.
This article is contributed by Rahul Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
The code for the above is given below:
4 5 6 7 8 9
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)
- Infix to Postfix using different Precedence Values for In-Stack and Out-Stack
- Find maximum in stack in O(1) without using additional stack
- Reverse a stack using recursion
- Spaghetti Stack
- Design and Implement Special Stack Data Structure | Added Space Optimized Version
- Implement Stack using Queues
- Iterative Postorder Traversal | Set 2 (Using One Stack)
- Design a stack with operations on middle element
- Sort a stack using recursion
- Design a stack that supports getMin() in O(1) time and O(1) extra space
- Implement a stack using single queue
- Stack Class in Java
- Stack | Set 2 (Infix to Postfix)
- Stack | Set 4 (Evaluation of Postfix Expression)
- Stack Data Structure (Introduction and Program)
- How to implement stack using priority queue or heap?
- Pattern Occurrences : Stack Implementation Java