当前位置:网站首页>每日一题:力扣: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(); */
边栏推荐
- UNI-Admin基础框架怎么关闭创建超级管理员入口?
- BarcodeX(ActiveX打印控件) v5.3.0.80 免费版使用
- [sciter]: encapsulate the notification bar component based on sciter
- Shell product written examination related
- Insert sort and Hill sort
- Common sense: what is "preservation" in insurance?
- [sdx62] wcn685x will bdwlan Bin and bdwlan Txt mutual conversion operation method
- Oracle Performance Analysis 3: introduction to tkprof
- GPS from getting started to giving up (XI), differential GPS
- 墨西哥一架飞往美国的客机起飞后遭雷击 随后安全返航
猜你喜欢

2020 Bioinformatics | GraphDTA: predicting drug target binding affinity with graph neural networks

【数字IC手撕代码】Verilog无毛刺时钟切换电路|题目|原理|设计|仿真

Adjustable DC power supply based on LM317

GPS从入门到放弃(十七) 、对流层延时

GNN,请你的网络层数再深一点~

Reset Mikrotik Routeros using netinstall

2021 geometry deep learning master Michael Bronstein long article analysis

硬件開發筆記(十): 硬件開發基本流程,制作一個USB轉RS232的模塊(九):創建CH340G/MAX232封裝庫sop-16並關聯原理圖元器件

2020 Bioinformatics | GraphDTA: predicting drug target binding affinity with graph neural networks

C#实现水晶报表绑定数据并实现打印4-条形码
随机推荐
设置状态栏样式Demo
MongoDB(三)——CRUD
Codeforces Round #274 (Div. 2) –A Expression
Wechat red envelope cover applet source code - background independent version - source code with evaluation points function
Unity3d Learning Notes 6 - GPU instantiation (1)
Anaconda installs third-party packages
MySQL related terms
GPS from getting started to giving up (12), Doppler constant speed
Management background --3, modify classification
C # realizes crystal report binding data and printing 4-bar code
Unity3d Learning Notes 6 - GPU instantiation (1)
[leetcode daily clock in] 1020 Number of enclaves
3DMax指定面贴图
Some problems about the use of char[] array assignment through scanf..
[sdx62] wcn685x will bdwlan Bin and bdwlan Txt mutual conversion operation method
HDU 2008 数字统计
AI 企业多云存储架构实践 | 深势科技分享
GPS从入门到放弃(十四)、电离层延时
2500个常用中文字符 + 130常用中英文字符
Adjustable DC power supply based on LM317