当前位置:网站首页>剑指 Offer 09. 用两个栈实现队列
剑指 Offer 09. 用两个栈实现队列
2022-07-28 10:28:00 【jjj34】
用到的知识点:创建栈,判断栈是否为空,栈的pop和push
1.创建栈
以整型为例
Stack<Integer> st;
st = new Stack<n>();
类比基础类型
int a;
a=5;Stack<Integer> st;Stack表明声明的容器是栈
Intege表明栈存储的变量为整数型
st为栈的名字
st = new Stack<n>();new创建对象
<n> 当n为具体的数时,如5,表明栈最多存5个变量
当n为空时,表明栈可以随便存,如下
st = new Stack<>()2.栈的函数
用到了empty(),pop(),push()
empty() 测试栈是否为空,返回boolean
st.empty();
pop() 出栈,返回被出栈元素的值
a = st.pop();
push(a) 将a入栈
st.push(a)其他的一些函数
peek() 查看栈顶部元素,但不移除它
search(a) 返回a在栈中的位置,以1为基数3.题解代码
class CQueue {
//队列:先进先出
//声明两个栈
private Stack<Integer> st1;
private Stack<Integer> st2;
public CQueue() {
st1=new Stack<>();//固定搭配 Stack<Interger> name=Stace<>()
st2=new Stack<>();
}
public void appendTail(int value) {
//判断第一个对列是否为空,空的话直接放进去
//非空就将数据全部移到2,放进去后在移回来
//采用while循环,直接全部放入2
while(!st1.empty())
{
st2.push(st1.pop());
}
st1.push(value);
while(!st2.empty())
{
st1.push(st2.pop());
}
}
public int deleteHead() {
//判断1是否为空
//空就null
//非空就pop
if(st1.empty())
{
return -1;
}
else
{
return st1.pop();
}
}
}
/**
* Your CQueue object will be instantiated and called as such:
* CQueue obj = new CQueue();
* obj.appendTail(value);
* int param_2 = obj.deleteHead();
*/边栏推荐
- markdown转成word或者pdf
- 产品端数据分析思维
- QT generation Exe file and run without QT environment (enigma virtual box for green executable software packaging) graphic tutorial
- Yan reports an error: exception message: /bin/bash: line 0: fg: no job control
- Install Office customization. Troubleshooting during installation
- C language input string with spaces
- PyQt5快速开发与实战 4.12 日历与时间
- Select without the order by clause, the order of the returned results is not reliable
- clo*******e:项目管理随记
- 5. Implement MapReduce program on window side to complete wordcount function
猜你喜欢

Yarn报错:Exception message: /bin/bash: line 0: fg: no job control

GKBillowNoiseSource

Two years of crud, two graduates, two months of preparation for the interview with ALI, and fortunately won the offer grading p6

Batch Normlization

3、MapReduce详解与源码分析

Attention attention mechanism flow chart

剑指 Offer 35. 复杂链表的复制

生成对抗网络在DeepFake中的未来
![[application of stack] - infix expression to suffix expression](/img/c1/879716342f6dd5eaa8b79c752eca16.png)
[application of stack] - infix expression to suffix expression

GKConstantNoiseSource
随机推荐
GKCoherentNoiseSource
GKPerlinNoiseSource
Codeforces Round #614 (Div. 2) A. ConneR and the A.R.C. Markland-N
GKPolygonObstacle
Codeforces Round #614 (Div. 2) B. JOE is on TV!
Operation log of dbeaver
Excel word simple skills sorting (continuous update ~)
GKCylindersNoiseSource
乱打日志的男孩运气怎么样我不知道,加班肯定很多
GKPerlinNoiseSource
c语言进阶篇:指针(一)
Select without the order by clause, the order of the returned results is not reliable
The Xiongguan pass is like an iron road, and now we are going to cross it from the beginning
蓝桥杯嵌入式-HAL库-SYSTICK
Arduino基础知识
Redis-day01-常识补充及redis介绍
PyQt5快速开发与实战 4.12 日历与时间
GKSphereObstacle
Excel word 简单 技巧 整理(持续更新 大概~)
剑指 Offer 35. 复杂链表的复制