当前位置:网站首页>【JZOF】09用两个栈实现队列
【JZOF】09用两个栈实现队列
2022-07-23 05:56:00 【叹了口丶气】
思路很简单:
借助栈的先进后出规则模拟实现队列的先进先出
1、当插入时,直接插入 stack1
2、当弹出时,当 stack2 不为空,弹出 stack2 栈顶元素,如果 stack2 为空,将 stack1 中的全部数逐个出栈入栈 stack2,再弹出 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 (!stack2.isEmpty()) {
return stack2.pop();
} else{
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}
边栏推荐
猜你喜欢

如何防止订单重复支付?

课程设计-推箱子C#(win form)

Eth trunk configuration instance learning record

User and group management, file permissions

Step on the electric render process renderer to solve the problem of require is not defined

信号完整性(SI)电源完整性(PI)学习笔记(三十二)电源分配网路(四)

Signal integrity (SI) power integrity (PI) learning notes (XXXI) power distribution network (III)

C语言-大端存储和小端存储

The context of virtual memory technology (Part 1)

Secret key remote login server to realize secret free login
随机推荐
linx的链接、一级目录、重定向、cp与mv
ACL——net
Query the cross compiled executable dependency Library
HCIA----05 RIP
Cortex-a series processor
信号完整性(SI)电源完整性(PI)学习笔记(三十二)电源分配网路(四)
踩坑electron渲染进程renderer,解决require is not defined的问题
HCIA----04 路由静态扩展、VLAN
C language - big end storage and small end storage
雷达导论PART VII.4 SAR系统设计
雷达导论PART VII.2 成像方法
Liveness, readiness and startup probes
数据进行脱敏
常见的cmd命令快速打开程序
App compilation and packaging deployment manual
Eth trunk configuration instance learning record
Redis distributed lock practice
课程设计-推箱子C#(win form)
雷达导论PART VII.3 SAR图像的形成和处理
当输入网址后,到网页显示,期间发生了什么