当前位置:网站首页>Using two stacks to implement queues [two first in first out is first in first out]
Using two stacks to implement queues [two first in first out is first in first out]
2022-06-27 23:58:00 【REN_ Linsen】
Queues are implemented with two stacks
Preface
The queue is characterized by first in, first out , The stack is characterized by last in, first out , If LIFO and then new stack , That's first in, first out .
One 、 Queues are implemented with two stacks
Two 、 Two in and out to get the queue
package everyday.simple;
import java.util.Stack;
// Two stacks realize the first in, first out of queues .
public class CQueue {
/* target: Use a LIFO stack Implement a first in first out queue . The way in and out of the stack and the way in the queue just want to change , If you put the elements in the stack on another stack , Then the order of this stack , Namely The first element enters the stack 1 The order of . */
Stack<Integer> in, out;
public CQueue() {
in = new Stack<>();
out = new Stack<>();
}
public void appendTail(int value) {
in.push(value);
}
public int deleteHead() {
// if in return, First of all , Make a good arrangement for the location of conditional visits , Try not to nest if and if else; second , Combine blocks of code that do the same thing under different conditions .
// Both stacks are empty
if (out.isEmpty() && in.isEmpty()) return -1;
// in There are elements in the stack , hold in All stack elements are taken out
if (out.isEmpty()) while (!in.isEmpty()) out.push(in.pop());
// out There are elements in the stack at this time , Just get it out of the stack .
return out.pop();
}
}
summary
reference
边栏推荐
猜你喜欢
零基础自学SQL课程 | IF函数
思源笔记订阅停止直接删云端数据嘛?
Excel print settings public header
零基础自学SQL课程 | SQL基本函数大全
[sword finger offer] 47 Maximum value of gifts
【PCL自学:Segmentation4】基于Min-Cut点云分割
[PCL self study: Segmentation3] PCL based point cloud segmentation: region growth segmentation
发射,接收天线方向图
c语言之字符串数组
智慧风电 | 图扑软件数字孪生风机设备,3D 可视化智能运维
随机推荐
MySQL character set
Is it safe for Huatai Securities to open an account online?
【AI应用】Jetson Xavier NX的详情参数
思源笔记订阅停止直接删云端数据嘛?
用两个栈实现队列[两次先进后出便是先进先出]
发射,接收天线方向图
[AI application] detailed parameters of Jetson Xavier nx
Chenyun pytorch learning notes_ Build RESNET with 50 lines of code
如何找到外文文献对应的中文文献?
计数质数[枚举 -> 空间换时间]
NDSS 2022 received list
圖的存儲結構
PAT乙级1013
【AI应用】NVIDIA GeForce RTX 1080Ti的详情参数
[AI application] detailed parameters of NVIDIA geforce RTX 3060
100 questions for an enterprise architect interview
Is it safe to open a stock account through the account opening QR code of CICC securities manager? Or is it safe to open an account in a securities company?
【PCL自学:Segmentation4】基于Min-Cut点云分割
At the beginning of reading English literature, I would like to ask you how you should read it in the first place?
Transmitting and receiving antenna pattern