算法-栈和队列:用栈实现队列 【C++|算法-栈和队列(用栈实现队列)】使用两个栈实现队列的功能:
- pop():弹出队头元素。
- peek():获取队头元素。
- push(x):从队尾添加元素。
- empty():队列是否为空。
#include
#include
using namespace std;
class MyQueue{
public:
stack stIn;
stack stOut;
//- push(x):从队尾添加元素。
void push(int x){
stIn.push(x);
}
//- pop():弹出队头元素。
int pop(){
int res;
if(true == stOut.empty()){//将stIn的元素全部出栈,进入stOut
while (false == stIn.empty()) {
stOut.push(stIn.top());
stIn.pop();
}
}
res = stOut.top();
stOut.pop();
return res;
}
//- peek():获取队头元素。
int peek(){
int res = this->pop();
//直接使用上述函数获取
stOut.push(res);
//因为弹出来了所以再放回去
return res;
}
//- empty():队列是否为空。
bool empty(){
if(stIn.empty() && stOut.empty()){
return true;
}
return false;
}
};
int main(){
MyQueue myQue;
myQue.push(1);
myQue.push(2);
myQue.push(3);
myQue.push(4);
cout<<"myQue.empty()=="<
推荐阅读
- C++|算法-字符串(反转字符串里的单词)
- FPGA学习笔记|FPGA学习笔记_图像处理6_FPGA实现 sobel算子边缘检测算法
- 机器学习|机器学习(七)过拟合问题与正则化
- C++|C++11/14之智能指针std::unique_ptr
- 玩转算法系列–图论精讲 面试升职必备(Java版)含源码ppt无mi分xiang
- 排序算法|归并排序(c语言)
- OpenCV|【opencv】最近邻插值、双线性插值、双三次插值(三次样条插值)
- Linux服务器开发|记录一次腾讯c/c++ linux后台开发岗面试经历(面试题含答案)
- python|某音jsvmp下参数分析笔记