3.4. queue via stack
This commit is contained in:
parent
844e359220
commit
2657eb6a80
|
|
@ -0,0 +1,25 @@
|
||||||
|
# 3.4. Queue via stacks
|
||||||
|
|
||||||
|
> Implement a MyQueue class which implements a queue using two stacks
|
||||||
|
|
||||||
|
## First idea
|
||||||
|
|
||||||
|
A stack is LIFO, first element to get out is the one inserted last. And queue is FIFO.
|
||||||
|
|
||||||
|
## Hints
|
||||||
|
|
||||||
|
* How to remove the oldest item from a stack if you only have access to the newest item?
|
||||||
|
* Delete the one opposite in the array, so the last one...
|
||||||
|
* The trick must be inverting something because I need two stacks...
|
||||||
|
* We can remove the oldest elem in a stack by repeatedly removing the newest item (inserting those in the temporary stack, stack \#2) until we get down to one element, then put all the elems back. This requires O(n). Can we optimize for scenarios where we might do several pops in a row?
|
||||||
|
* If we could check if an elem is present in stack \#2 yes, but there's no such function
|
||||||
|
|
||||||
|
## Solution
|
||||||
|
|
||||||
|
We need to modify `peek` and `pop` to work in reverse order. We can use stack \#2 to reverse the order of the elements by popping s1 and pushing the elements on to s2. In each `peek` and `pop` operation, we pop everything from s1 onto s2, perform `peek` and `pop` and then push everything back.
|
||||||
|
|
||||||
|
If two `peek`/`pop` must be performed, we need to move everything again. In a lazy approach, all elemenst remain in s2 until they must absolutely be reversed.
|
||||||
|
|
||||||
|
stack_newest has the newest elements on top and stack_oldest has the oldest elements on top. When we dequeue an element, we dequeue from stack_oldest. If empty, transfer all elemens from stack_newest into stack_oldest in reverse order.
|
||||||
|
|
||||||
|
[Code in Github](https://github.com/careercup/CtCI-6th-Edition/blob/master/Java/Ch%2003.%20Stacks%20and%20Queues/Q3_04_Queue_via_Stacks/MyQueue.java)
|
||||||
Loading…
Reference in New Issue