用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
两个栈 stack1 和 stack2:
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
if(stack1.isEmpty() && stack2.isEmpty())
throw new RuntimeException("Queue is empty!");
int node;
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
node = stack1.pop();
stack2.push(node);
}
}
return stack2.pop();
}
}
版权属于: 尾尾部落
原文地址: https://cloud.tencent.com/developer/article/1327741
转载时必须以链接形式注明原始出处及本声明。
window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"1","bdSize":"24"},"share":{}};with(document)0[(getElementsByTagName('head')0||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];