首页 > 代码库 > 225. Implement Stack using Queues

225. Implement Stack using Queues

题目:

Implement the following operations of a stack using queues.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • empty() -- Return whether the stack is empty.

Notes:

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

链接: http://leetcode.com/problems/implement-stack-using-queues/

2/25/2017, Java

主要想法是,pop(), top()基本上是同样的东西用两次,所以麻烦的事情放在push()里来做。

注意Queue interface本身是没有size()函数的,这个size()是来自LinkedList的函数,恰好题目允许。

 1 public class MyStack {
 2     Queue<Integer> q = new LinkedList<Integer>();
 3 
 4     /** Initialize your data structure here. */
 5     public MyStack() {
 6         
 7     }
 8     
 9     /** Push element x onto stack. */
10     public void push(int x) {
11         int size = q.size();
12         Integer val;
13         q.add(x);
14         for (int i = 0; i < size; i++) {
15             val = q.poll();
16             q.add(val);
17         }
18     }
19     
20     /** Removes the element on top of the stack and returns that element. */
21     public int pop() {
22         return q.poll();
23     }
24     
25     /** Get the top element. */
26     public int top() {
27         return q.peek();
28     }
29     
30     /** Returns whether the stack is empty. */
31     public boolean empty() {
32         return q.isEmpty();
33     }
34 }
35 
36 /**
37  * Your MyStack object will be instantiated and called as such:
38  * MyStack obj = new MyStack();
39  * obj.push(x);
40  * int param_2 = obj.pop();
41  * int param_3 = obj.top();
42  * boolean param_4 = obj.empty();
43  */

 

225. Implement Stack using Queues