代码随想录算法训练营第十天【栈与队列】232.用栈实现队列、225.用队列实现栈
232.用栈实现队列
心得:思路不难,栈和队列的特性要掌握
1)栈,先进后出;队列,先进先出
2)初始化一个栈,Stack<Integer> stack = new Stack<>()
3)放入元素,stack.push()
4)弹出栈顶元素,stack.pop()
5)获取栈顶元素但不弹出,stack.peek()
6)判断栈是否为空,stack.isEmpty()
class MyQueue { Stack<Integer> stackIn; Stack<Integer> stackOut; public MyQueue() { stackIn = new Stack<>(); stackOut = new Stack<>(); } public void push(int x) { stackIn.push(x); } public int pop() { if(stackOut.isEmpty()){ while(!stackIn.isEmpty()){ stackOut.push(stackIn.pop()); } } return stackOut.pop(); } public int peek() { int result = this.pop(); stackOut.push(result); return result; } public boolean empty() { return stackIn.isEmpty() && stackOut.isEmpty(); } } /** * Your MyQueue object will be instantiated and called as such: * MyQueue obj = new MyQueue(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.peek(); * boolean param_4 = obj.empty(); */
225.用队列实现栈
心得:掌握队列的基本方法,关注pop()的实现方式
1)在队列后面增加x,deque.addLast(x)
2)获取队列的第一个值,但不弹出,deque.peekFirst()
3)弹出队列的第一个值,deque.pollFirst()
class MyStack { Deque<Integer> deque; public MyStack() { deque = new ArrayDeque<>(); } public void push(int x) { deque.addLast(x); } public int pop() { int move = deque.size()-1; while (move-- > 0) { deque.addLast(deque.pollFirst()); } return deque.pollFirst(); } public int top() { return deque.peekLast(); } public boolean empty() { return deque.isEmpty(); } } /** * Your MyStack object will be instantiated and called as such: * MyStack obj = new MyStack(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.top(); * boolean param_4 = obj.empty(); */
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?