Implement Queue using Stacks 解答

Question

Implement the following operations of a queue using stacks.

  • push(x) -- Push element x to the back of queue.
  • pop() -- Removes the element from in front of queue.
  • peek() -- Get the front element.
  • empty() -- Return whether the queue is empty.

Notes:

    • You must use only standard operations of a stack -- which means only push to toppeek/pop from topsize, and is empty operations are valid.
    • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
    • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

Solution

enQueue(q,  x)
  1) Push x to stack1 (assuming size of stacks is unlimited).

deQueue(q)
  1) If both stacks are empty then error.
  2) If stack2 is empty
       While stack1 is not empty, push everything from satck1 to stack2.
  3) Pop the element from stack2 and return it.

Check each element i, i can only be pushed/ poped once at stack 1, and pushed/ poped once at stack 2. So add(), remove(), peek() still cost O(1) time.

 1 public class Queue {
 2     private Stack<Integer> stack1;
 3     private Stack<Integer> stack2;
 4 
 5     public Queue() {
 6        stack1 = new Stack<Integer>();
 7        stack2 = new Stack<Integer>();
 8     }
 9     
10     public void push(int element) {
11         stack1.push(element);
12     }
13 
14     public int pop() {
15         if (stack1.isEmpty() && stack2.isEmpty())
16             return 0;
17         if (stack2.isEmpty()) {
18             while (!stack1.isEmpty())
19                 stack2.push(stack1.pop());
20         }
21         return stack2.pop();
22     }
23 
24     public int top() {
25         if (stack1.isEmpty() && stack2.isEmpty())
26             return 0;
27         if (stack2.isEmpty()) {
28             while (!stack1.isEmpty())
29                 stack2.push(stack1.pop());
30         }
31         return stack2.peek();
32     }
33 }

 

posted @ 2015-10-09 05:36  树獭君  阅读(187)  评论(0编辑  收藏  举报