当前位置:网站首页>Stack simulation queue
Stack simulation queue
2022-07-25 22:48:00 【Cool hair】
The characteristic of the stack : Last in, first out (Last In First Out)
The characteristics of the queue are : fifo (First In First Out)
The idea of simulating queues with stacks : First define two stacks in and out, With the stack in To store elements , Stack out To output elements , Press into the stack in order when entering the team in in , From the stack in Pop up and press into the stack out in , According to the characteristics of stack , Stack in order out Just get the elements out of the stack . The specific implementation is as follows :
public static void main(String[] args) {
MyQueue<String> queue = new MyQueue<String>();
queue.offer("A1");
queue.offer("A2");
queue.offer("A3");
queue.offer("A4");
queue.offer("A5");
System.out.println(queue.poll() + " Out of the team ");
// Traverse
while (!queue.isEmpty()) {
System.out.println(queue.poll());
}
}
}
// Use stack to simulate queue
class MyQueue<E> {
private Stack<E> in = new Stack<E>(); // Join the team
private Stack<E> out = new Stack<E>(); // Out of the stack
// The team
public void offer(E e) {
while (!out.isEmpty()) {
in.push(out.pop());
}
in.push(e);
}
public boolean isEmpty() {
return in.size() == 0 && out.size() == 0;
}
// Out of the team
public E poll() {
while (!in.isEmpty()) {
out.push(in.pop());
}
return out.pop();
}Be careful : Make sure to stack when joining the team out There's no element in it , That is, put them all on the stack in in , When leaving the team, you should also ensure that the stack in There are no elements in it , That is, all out of the team !!
边栏推荐
猜你喜欢
![[文献阅读] - HRL -[HRL with Universal Policies for Multi-Step Robotic Manipulation]](/img/34/06d5ba3af4e6e775a335324c020161.png)
[文献阅读] - HRL -[HRL with Universal Policies for Multi-Step Robotic Manipulation]

Qt中文编程遇C2001错误,提示“常量中有换行符”

Kibana~ the process number cannot be found after kibana is started in the background

Multi data source switching

CUDA environment construction

自媒体人必备的4个素材网站,再也不用担心找不到素材

Kibana~后台启动Kibana之后无法找到进程号
![[PMP learning notes] Chapter 1 Introduction to PMP System](/img/80/144124af40f0a015c4deafc3aa7432.png)
[PMP learning notes] Chapter 1 Introduction to PMP System

xss-工具-Beef-Xss安装以及使用

Mocha test
随机推荐
Opencv compile and call GPU version
JVM memory area
ML-Numpy
Tfrecord write and read
JVM内存区域
Vs2019 WinForm clr20r3 error
LabVIEW develops PCI-1680U dual port can card
QVariant的使用
MySQL data type
ECMA 262 12 Lexical Grammer
Madness. Smbms (supermarket order management system)
What is the difference between bio, NiO and AIO?
Two methods of printing strings in reverse order in C language
Von Neumann architecture
Why should we launch getaverse?
Domain oriented model programming
Can generic types be used in array
Data type conversion
The new media operation strategy (taking xiaohongshu as an example) helps you quickly master the creative method of popular models
Node.js operation database