LeetCode上面的一道题目,原文如下:
Implement the following operations of a queue using stacks.
push
to top
, peek/pop from top
, size
,
and is empty
operations are valid.代码如下:
class MyQueue { // Push element x to the back of queue. Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); public void push(int x) { stack1.push(x); } // Removes the element from in front of queue. public void pop() { if(stack2.size()==0) { int m = stack1.size(); for(int i=0;i<m;i++) { stack2.push(stack1.pop()); } } stack2.pop(); } // Get the front element. public int peek() { if(stack2.size()==0) { int m = stack1.size(); for(int i=0;i<m;i++) { stack2.push(stack1.pop()); } } return stack2.peek(); } // Return whether the queue is empty. public boolean empty() { return stack1.size()==0&&stack2.size()==0; } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/snchenjt/article/details/46874771