232. Implement Queue using Stacks

题目:

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).

链接: http://leetcode.com/problems/implement-queue-using-stacks/

2/28/2017

 1 public class MyQueue {
 2     Stack<Integer> s;
 3     Stack<Integer> t;    
 4     /** Initialize your data structure here. */
 5     public MyQueue() {
 6         s = new Stack<Integer>();
 7         t = new Stack<Integer>();    
 8     }
 9     
10     /** Push element x to the back of queue. */
11     public void push(int x) {
12         if (s.isEmpty()) s.push(x);
13         else {
14             while (!s.isEmpty()) {
15                 t.push(s.pop());
16             }
17             s.push(x);
18             while (!t.isEmpty()) {
19                 s.push(t.pop());
20             }
21         }        
22     }
23     
24     /** Removes the element from in front of queue and returns that element. */
25     public int pop() {
26         return s.pop();        
27     }
28     
29     /** Get the front element. */
30     public int peek() {
31         return s.peek();        
32     }
33     
34     /** Returns whether the queue is empty. */
35     public boolean empty() {
36        return s.isEmpty();        
37     }
38 }

 

posted @ 2017-03-01 05:28  panini  阅读(122)  评论(0编辑  收藏  举报