当前位置:网站首页>Leetcode - 225 implements stack with queue
Leetcode - 225 implements stack with queue
2022-07-25 15:40:00 【Cute at the age of three @d】


Use two queues

class MyStack {
// Use two queues to implement the stack
// Home line
private Deque<Integer> deque1;
// Secondary queue
private Deque<Integer> deque2;
public MyStack() {
deque1 = new LinkedList<>();
deque2 = new LinkedList<>();
}
public void push(int x) {
// First, put all the values of the main queue into the auxiliary queue
while(deque1.size() != 0){
deque2.offerLast(deque1.pollFirst());
}
// take x Enter the main queue
deque1.offerLast(x);
// Put the value of the secondary queue back into the primary queue
while(deque2.size() != 0){
deque1.offerLast(deque2.pollFirst());
}
// At this time, those who enter the queue later x Already at the head of the team
}
public int pop() {
return deque1.pollFirst();
}
public int top() {
return deque1.peekFirst();
}
public boolean empty() {
return deque1.size() == 0;
}
}
Use a queue

class MyStack {
// Use a queue to implement stack
private Deque<Integer> deque;
public MyStack() {
deque = new LinkedList<>();
}
public void push(int x) {
// How many values are currently in the queue
int qsize = deque.size();
// take x Queue entry
deque.offerLast(x);
// Put in front of the queue qsize Values are placed at the end of the queue
while(qsize > 0){
deque.offerLast(deque.pollFirst());
qsize--;
}
// At this time, those who enter the queue later x Already at the head of the team
}
public int pop() {
return deque.pollFirst();
}
public int top() {
return deque.peekFirst();
}
public boolean empty() {
return deque.size() == 0;
}
}
边栏推荐
- Box avoiding mouse
- 哪里有搭建flink cdc抽mysql数的demo?
- Binary complement
- Cf750f1 thinking DP
- matlab 如何保存所有运行后的数据
- Cf365-e - Mishka and divisors, number theory +dp
- 分布式 | 实战:将业务从 MyCAT 平滑迁移到 dble
- Phased summary of the research and development of the "library management system -" borrowing and returning "module
- LeetCode - 677 键值映射(设计)*
- No tracked branch configured for branch xxx or the branch doesn‘t exist. To make your branch trac
猜你喜欢
随机推荐
2016 CCPC network trial c-change root DP good question
Pytorch学习笔记--常用函数总结3
The difference between Apple buy in and apple pay
ML - natural language processing - Basics
Distributed principle - what is a distributed system
C # fine sorting knowledge points 10 generic (recommended Collection)
Box avoiding mouse
带你创建你的第一个C#程序(建议收藏)
理解“平均负载”
matlab randint,Matlab的randint函数用法「建议收藏」
Pytorch学习笔记--SEResNet50搭建
MySQL—常用SQL语句整理总结
JVM—类加载器和双亲委派模型
Xcode added mobileprovision certificate file error: Xcode encoded an error
ZOJ - 4114 flipping game DP, reasonable state representation
CF750F1-思维dp
Cf365-e - Mishka and divisors, number theory +dp
《图书馆管理系统——“借书还书”模块》项目研发阶段性总结
Flex layout
数据系统分区设计 - 请求路由









