当前位置:网站首页>Jianzhi offer 09. realize queue with two stacks
Jianzhi offer 09. realize queue with two stacks
2022-07-28 10:54:00 【jjj34】
Knowledge points used : Create a stack , Judge whether the stack is empty , Stack pop and push
1. Create a stack
Take integer as an example
Stack<Integer> st;
st = new Stack<n>();
Analogy base type
int a;
a=5;Stack<Integer> st;Stack Indicates that the declared container is a stack
Intege Indicates that the variables stored in the stack are of integer type
st Is the name of the stack
st = new Stack<n>();new Create objects
<n> When n For a specific number of hours , Such as 5, Indicates that the stack can store at most 5 A variable
When n It's empty time , Indicates that the stack can be stored casually , as follows
st = new Stack<>()2. Stack function
Yes empty(),pop(),push()
empty() Test if the stack is empty , return boolean
st.empty();
pop() Out of the stack , Return the value of the element out of the stack
a = st.pop();
push(a) take a Push
st.push(a)Some other functions
peek() Look at the top element of the stack , But don't remove it
search(a) return a Position in the stack , With 1 Cardinal number 3. Solution code
class CQueue {
// queue : fifo
// Declare two stacks
private Stack<Integer> st1;
private Stack<Integer> st2;
public CQueue() {
st1=new Stack<>();// fixed collocation Stack<Interger> name=Stace<>()
st2=new Stack<>();
}
public void appendTail(int value) {
// Judge whether the first pair of columns is empty , If it's empty, put it directly
// If it is not empty, move all the data to 2, Put it in and move it back
// use while loop , Put it all directly 2
while(!st1.empty())
{
st2.push(st1.pop());
}
st1.push(value);
while(!st2.empty())
{
st1.push(st2.pop());
}
}
public int deleteHead() {
// Judge 1 Is it empty
// Empty null
// It's not empty 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();
*/边栏推荐
猜你喜欢
随机推荐
ICML 2022 | graph represents the structure aware transformer model of learning
Install GMP
Start from scratch blazor server (2) -- consolidate databases
国内外优秀程序员的博客全在这了,请查收
判断数码管是共阳极还是共阴极
GKBillowNoiseSource
图片滑动特效
The blogs of excellent programmers at home and abroad are all here, please check it
GKRandom
这里有一份超实用Excel快捷键合集(常用+八大类汇总)
学会这些分析方法及模型,遇到问题不再没思路
1. Sum of two numbers
Andorid development III (intent)
nodejs:搭建express 服务,设置session以及实现退出操作
The Xiongguan pass is like an iron road, and now we are going to cross it from the beginning
从零开始Blazor Server(2)--整合数据库
Tree Shaking和DCE
Characteristics and installation of non relational database mongodb
Yan reported an error: could not find any valid local directory for nmprivate/
剑指 Offer 09. 用两个栈实现队列









