首先了解栈和队列
什么是栈?(水级理解!
什么是队列 灌水理解
232.用栈实现队列
依据栈实现队列的几个函数!
(可以使用栈中的函数!)
代码入下
先定义两个栈实现队列
stack<int> sin;
stack<int> sout;
void push(int x) 将元素 x 推到队列的末尾
void push(int x) {
sin.push(x);//栈的push实现队列push
}
int pop() 从队列的开头移除并返回元素
int pop() {
if(sout.empty())
{
while( sin.empty() == NULL)//empty判断空为1,不是空为0!直到sin为空!!
{
sout.push(sin.top());
sin.pop();
}
}
int temp=sout.top();
sout.pop();
return temp;
}
int peek() 返回队列开头的元素
int peek() {
int a=this->pop();//两个栈实现队列!!不能直接top
sout.push(a);
return a;
}
boolean empty() 如果队列为空,返回 true ;否则,返回 false
bool empty() {
return sin.empty()&&sout.empty();//两个栈实现队列!判断两个栈
}
完整代码
class MyQueue {
public:
stack<int> sin;
stack<int> sout;
MyQueue() {
}
void push(int x) {
sin.push(x);
}
int pop() {
if(sout.empty())
{
while( sin.empty() == NULL)//直到sin为空!!
{
sout.push(sin.top());
sin.pop();
}
}
int temp = sout.top();
sout.pop();
return temp;
}
int peek() {
int a=this->pop();//两个栈实现队列!!
sout.push(a);
return a;
}
bool empty() {
return sin.empty()&&sout.empty();
}
};
225.用队列实现栈
参照栈实现队列
class MyStack {
public:
queue <int> duilie;
MyStack() {
}
void push(int x) {
duilie.push(x);
}
int pop() {
int n=duilie.size()-1;
while(n--)
{
duilie.push(duilie.front());
duilie.pop();
}
int temp=duilie.front();
duilie.pop();
return temp;
}
int top() {
return duilie.back();// int a=this->pop();
// duilie.push(a);
// return a;
}
bool empty() {
return duilie.empty();
}
};
我是小白,但我要成为小亮(光头了自会反光)