Reputation: 179
I want to use an empty stack S to check whether a Queue Q contaitns element x, thus my solution was to copy elements of Q into S and check if contain x, but I'm also asked to return S elements into Q again as it was originaly, this must be done using only a Q and S without any other arrays of SL, so I have written this algorithm:
Boolean found ← false
int element ← 0
While(Q is not empty)
element ← Q.dequeue()
if(element equal x)
found ← true
S.push(element)
While(S is not empty)
( elements back to Q) ?
stuck in last step, if I used Q.enqueue(S.pop) then the order of elements in Q will be reversed
Upvotes: 0
Views: 1416
Reputation: 449
I am not sure how java default Queue work.
Upvotes: 0
Reputation: 343
Correct, the order will be reversed. This means that if you repeat the algorithm yet again (all to S and back to Q) you will reverse it yet again, meaning you will get back to the original order of elements, which is what you want.
Upvotes: 1
Reputation: 2868
This feels like a HW question so I won't solve it for you, but I will give you a hint - what happens when you dequeue a queue into a stack and then dequeue the stack back to the queue?
How can you use that phenomena to restore the original queue?
Upvotes: 1
Reputation: 726599
if I used
Q.enqueue(S.pop)
then the order of elements in Q will be reversed
That's right, it will be reversed. You can use it to your advantage by observing that once you run the same loop again, you would get the original order back.
You can avoid writing the same loop twice if you make a method that does the search, and leaves the queue in reversed state. You can call your search method twice, and ignore the second return value.
Upvotes: 1