![]() |
VOOZH | about |
Design a stack with the following operations.
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 the following steps.
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.
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.
The code for the above is given below:
4 5 6 7 8 9
Time Complexity : O(1) , as all operation use constant time.
Auxiliary Space : O(1) , since no extra space used.