当前位置:网站首页>剑指offer 05 两个栈实现队列
剑指offer 05 两个栈实现队列
2022-07-23 05:45:00 【wzf6667】
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路分析
比如我push 1,2,3 ,pop ,pop,push4,5,pop,pop,pop
结果应该为1,2,3,4,5(先入先出)
- 每次push都在stack1 push进去,重点是每次pop的时候
我们先把stack1里面的数值都pop进stack2里,比如stack1 中由栈顶到栈底存放着3,2,1,那么stack2中就应该存放着1,2,3,也就是队列的顺序。 - 数据更替完之后,stack1为空,stack2存放着正确的顺序,这时pop走队列的第一个,然后再把剩下的重新倒回stack1中(如果不放回去下次再push的时候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() {
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
int first = stack2.pop();
while(!stack2.isEmpty()){
stack1.push(stack2.pop());
}
return first;
}
}
边栏推荐
- Interpretation of the paper: develop a prediction model based on multi-layer deep learning to identify DNA N4 methylcytosine modification
- TeX or LaTeX or MikTeX or TeX Live or CTeX
- Vs attribute configuration related knowledge
- 1. Ten principles of Economics
- Prometheus
- 基于UDP的群聊聊天室
- [AUTOSAR com 3. signal sending and receiving process tx/rx]
- Upper and lower case letter conversion
- Redis——配置及应用
- Basic OJ exercise of binary tree-
猜你喜欢

OSI开放系统互联模型和TCP/IP模型
![[AUTOSAR com 2. Advanced introduction to communication protocol stack]](/img/d2/16b58126a160a13e22eb8158f5ec8c.png)
[AUTOSAR com 2. Advanced introduction to communication protocol stack]

【Autosar DEM 四.Event Memory】
![[AUTOSAR DEM iv.event memory]](/img/11/78ab6e5e49aa24f061e0f431112fc2.png)
[AUTOSAR DEM iv.event memory]

Redis——配置及应用

【AUTOSAR COM 3.信号的收发流程TX/RX】

常见的排序方法—选择排序

高等代数100道题及答案解析

Redis——基础概念

Talent column | can't use Apache dolphin scheduler? The most complete introductory tutorial written by the boss in a month
随机推荐
[AUTOSAR com 3. signal sending and receiving process tx/rx]
高电压技术基础知识
[AUTOSAR cantp 1. learn the network layer protocol of UDS diagnosis]
The CUDA version of pytorch installed by anconda is inconsistent with the CUDA version of the system
视频编解码相关资料汇总
钢结构基本原理试题及答案
Doubts about using the incluxdb database
Interpretation of the paper: "i4mc deep: intelligent prediction of N4 methylcytosine sites using deep learning methods with chemical properties"
Prometheus
Examen des principes fondamentaux de la structure en acier
【Autosar CP通用 1.如何阅读Autosar官方文档】
Summary of video coding and decoding related data
Review of basic principles of steel structure
Enter the triangle side length and calculate the area
解决谷歌chrome浏览器双击没反应,不能启动(亲测好用)
Baidu Shen Shuo: focus on the scene, deeply cultivate the industry, and bring practical results to enterprise Digitalization
[physical layer of CAN bus] 1. Content sharing of can/canfd sampling points
Desktop remote protocol - codec
C语言:详细讲解基于tcp和udp的两种本地通信方式
动态规划——“换硬币问题”