Q.enqueue(5) Q.enqueue(2) Q.dequeue() Q.enqueue(3) Q.dequeue()
for (int k = 1; k ≤ 7; k++) Q.enqueue(k); for (int k = 1; k ≤ 7; k++) Q.enqueue(Q.dequeue());
Final answer:
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
4 | 5 | 6 | 7 | 1 | 2 | 3 |
public Queue<String> contains(Queue<String> q, String str)
that takes a Queue and an element and returns true if the Queue contains this element or false if not. The elements in the Queue must remain in their original order once this method is complete.
public Queuecontains(Queue q, String str){ Queue temp = new Queue (); boolean found = false; while(!q.isEmpty()){ String curr = q.dequeue(); if(curr.equals(str)){ found = true; } temp.enqueue(curr); } while(!temp.isEmpty()){ q.enqueue(temp.dequeue()); } return found; }
To implement a queue using two stacks, consider one stack to be "input" and one stack to be "output". At any given point, all your elements are either in one stack or the other. When you are enqueuing elements, just push them onto the input stack. When you are dequeuing elements, pop all the elements from the input stack and push them onto the output stack. Then pop the top element from the output stack to get the dequeued element. The worst-case runtime complexity of dequeue is O(n).