当前位置:网站首页>每日一题:力扣:225:用队列实现栈
每日一题:力扣:225:用队列实现栈
2022-07-06 14:23:00 【会飞的猫不吃鱼】
题目
** 解析:用两个队列实现栈的结构,我们需要q1和q2,q1时刻与栈保持一致,q2用来起到一个辅助的作用。两者唯一的区别就是添加元素的区别,队列和栈的顺序应该是相反的,因此,q2的作用就显示出来了,每当栈添加一个元素的时候,q2添加该元素,然后将q1中的元素依次出队列,再进入q2。再讲q2和q1交换,以保证q1时刻与栈中元素保持一致。**
class MyStack {
public MyStack() {
}
Queue <Integer> q1 = new LinkedList<>();
Queue <Integer> q2 = new LinkedList<>();
public void push(int x) {
q2.offer(x);
while(!q1.isEmpty()){
q2.offer(q1.poll());
}
Queue <Integer> temp;
temp = q2;
q2 = q1;
q1 = temp;
}
public int pop() {
return q1.poll();
}
public int top() {
return q1.peek();
}
public boolean empty() {
return q1.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(); */
边栏推荐
- Kohana database
- Support multiple API versions in flask
- GNN, please deepen your network layer~
- [sdx62] wcn685x will bdwlan Bin and bdwlan Txt mutual conversion operation method
- GPS從入門到放弃(十三)、接收機自主完好性監測(RAIM)
- What is the difference between animators and animators- What is the difference between an Animator and an Animation?
- MariaDb数据库管理系统的学习(一)安装示意图
- Codeforces Round #274 (Div. 2) –A Expression
- HDU 2008 数字统计
- 嵌入式常用计算神器EXCEL,欢迎各位推荐技巧,以保持文档持续更新,为其他人提供便利
猜你喜欢
Some problems about the use of char[] array assignment through scanf..
2500个常用中文字符 + 130常用中英文字符
Seata聚合 AT、TCC、SAGA 、 XA事务模式打造一站式的分布式事务解决方案
微信红包封面小程序源码-后台独立版-带测评积分功能源码
[10:00 public class]: basis and practice of video quality evaluation
C#实现水晶报表绑定数据并实现打印4-条形码
HDR image reconstruction from a single exposure using deep CNNs阅读札记
RESNET rs: Google takes the lead in tuning RESNET, and its performance comprehensively surpasses efficientnet series | 2021 arXiv
硬件开发笔记(十): 硬件开发基本流程,制作一个USB转RS232的模块(九):创建CH340G/MAX232封装库sop-16并关联原理图元器件
[asp.net core] set the format of Web API response data -- formatfilter feature
随机推荐
[10:00 public class]: basis and practice of video quality evaluation
GPS从入门到放弃(十四)、电离层延时
Powerful domestic API management tool
Some problems about the use of char[] array assignment through scanf..
GPS从入门到放弃(十三)、接收机自主完好性监测(RAIM)
保存和检索字符串
插入排序与希尔排序
GPS从入门到放弃(十二)、 多普勒定速
Management background --2 Classification list
GPS from getting started to giving up (19), precise ephemeris (SP3 format)
UNI-Admin基础框架怎么关闭创建超级管理员入口?
搜素专题(DFS )
GPS from getting started to giving up (16), satellite clock error and satellite ephemeris error
Report on technological progress and development prospects of solid oxide fuel cells in China (2022 Edition)
LeetCode刷题(十一)——顺序刷题51至55
QT | UDP broadcast communication, simple use case
Shortcut keys in the terminal
GPS from getting started to giving up (XVIII), multipath effect
GPS从入门到放弃(十九)、精密星历(sp3格式)
[leetcode daily clock in] 1020 Number of enclaves