标签:removes get pre log tac boolean sum poll long
题目:
Implement the following operations of a stack using queues.
Notes:
push to back
, peek/pop from front
, size
, and is empty
operations are valid.链接: 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
标签:removes get pre log tac boolean sum poll long
原文地址:http://www.cnblogs.com/panini/p/6443558.html