当前位置:网站首页>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;
}
}
边栏推荐
猜你喜欢

ML - Speech - advanced speech model

带你创建你的第一个C#程序(建议收藏)

MySQL—常用SQL语句整理总结

GAMES101复习:三维变换

小波变换--dwt2 与wavedec2

Distributed principle - what is a distributed system

Understanding the difference between wait() and sleep()

Pytorch学习笔记--SEResNet50搭建

Get the ask code corresponding to the key pressed by the keyboard

Box avoiding mouse
随机推荐
MySQL - Summary of common SQL statements
LeetCode - 622 设计循环队列 (设计)
微信小程序
2016 CCPC network trial c-change root DP good question
JS URLEncode function
window系统黑窗口redis报错20Creating Server TCP listening socket *:6379: listen: Unknown error19-07-28
如何实现页面包含
二进制补码
如何解决跨域问题
组件化和模块化
Pat grade a 1152 Google recruitment (20 points)
ICPC2021昆明M-暴力+主席树
Qtime definition (manual waste utilization is simple and beautiful)
Games101 review: linear algebra
P4552 differential
Cf566a greed + dictionary tree
LeetCode - 232 用栈实现队列 (设计 双栈实现队列)
Pat class a topic directory
C#精挑整理知识要点10 泛型(建议收藏)
Brain racking CPU context switching