您的位置:首页 > 其它

lintcode&九章算法——Lintcode No.40 用栈实现队列 ? 待解决

2017-12-28 10:43 405 查看
原文:fourierhai

链接:http://mp.weixin.qq.com/s/ssAc1AodazaVtjRnFsTTgQ

Lintcode No.40 用栈实现队列



代码实现:

public class MyQueue{
private Stack<Integer> stack1;
private Stack<Integer> stack2;
public MyQueue() {
// do intialization if necessary
stack1 = new Stack<Integer>();
stack2 = new Stack<Integer>();
}
/*
* @param element: An integer
*
* @return: nothing
*/
public void push(int element) {
// write your code here
stack1.push(element);
}
/*
* @return: An integer
*/
public int pop() {
// write your code here
if (stack2.empty()) {
while (!stack1.empty()) {
int s1 = stack1.pop();
stack2.push(s1);
}
}
return stack2.pop();
}
/*
* @return: An integer
*/
public int top() {
// write your code here
if (stack2.empty()) {
while (!stack1.empty()) {
int s1 = stack1.pop();
stack2.push(s1);
}
}
return stack2.peek();
}
}


AC时间:在2500ms左右。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  class