Say that we want to maintain both a Stack and a Queue of the same elements. A ne
ID: 671000 • Letter: S
Question
Say that we want to maintain both a Stack and a Queue of the same elements. A new element that arrives implies a Push to the stack and a ENQUEUE to the Queue. Any Pop operation should remove the element from the QUEUE and from the Stack as well (even though its not the highest propriety element). Dequeue removes the head of the queue, but also removes this element from the Stack (even though its not the last to being inserted). Using two copies of every element and using additional pointers between element, show that we can implement both a stack and a queue so that every operation requires O(1) time.
(In all algorithm, always explain how and why they work. ALWAYS, analyze the running time complexity of your algorithms. In all algorithms, always try to get the fastest possible. A correct algorithm with slow running time may not get full credit. Always give arguments as for why what you did is correct. You can not just answer ”yes” or ”no”. NEVER write a program. Only write algorithm in the pseudocode we learned)
Explanation / Answer
Hope My solution may helps you..
Please let me know if you have any issue.
start
for(int i;element){
EnQueue->Queue
Push->Stack
pop->Stack
Deque->Queue
}
Time Complexicity of O(2n)
which means O(n+n).same time takes for both stack and Queue