用两个栈实现队列

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() {
//将第一个栈中内容弹出放入第二个栈中
while(!stack1.isEmpty())
stack2.push(stack1.pop());
//第二个栈栈顶就是最先进来的元素,即队首
int res = stack2.pop();
//再将第二个栈的元素放回第一个栈
while(!stack2.isEmpty())
stack1.push(stack2.pop());
return res;
}
}

 

参考:https://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6?tpId=295&tqId=23281&ru=/exam/oj&qru=/ta/format-top101/question-ranking&sourceUrl=%2Fexam%2Foj

posted @   northli  阅读(10)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
历史上的今天:
2021-11-26 list sort排序
点击右上角即可分享
微信分享提示