定义两个栈,一个输入栈,一个输出栈
push操作时,直接push操作即可
pop操作时,得考虑输出栈是否为空,如果为空,得先将输入栈的数据全部导入到输出栈,再从输出栈弹出数据;如果不为空,直接弹出数据即可。
peek操作时,也得和pop操作一样考虑。
返回数据时,得
int res=stack_out.top();
return res;
int result=stack_out.top();
stack_out.pop();
return result;
否则容易出错
class MyQueue {
public:
//定义两个栈
stack<int> stack_in;
stack<int> stack_out;
MyQueue() {
}
void push(int x) {
stack_in.push(x);
}
int pop() {
if(stack_out.empty()){
while(!stack_in.empty()){
stack_out.push(stack_in.top());
stack_in.pop();
}
}
int result=stack_out.top();
stack_out.pop();
return result;
}
int peek() {
if(stack_out.empty()){
while(!stack_in.empty()){
stack_out.push(stack_in.top());
stack_in.pop();
}
}
int res=stack_out.top();
return res;
// int res=this->pop();
// stack_out.push(res);
// return res;
}
bool empty() {
// if(stack_out.empty()) return true;
// else return false;
return stack_in.empty() && stack_out.empty();
}
};
方法一:两个单端队列设计模拟栈
push操作时,直接push进去就可以了
pop操作时,操作稍微复杂一点。
获取队列的大小len,接着大小len先行减1(为了保留该队列的最后一个元素)
接着除了所保留的最后一个元素,其余元素全部push进q.out队列中
将所保留的最后一个元素赋给res,并弹出最后一个元素,返回即可。将队列q.out赋给q.in,并清空q.out
peek操作,就直接返回q.in队列的back尾部即可(因为不要求弹出去,所以可以使用这个操作)
empty()操作,因为前面已经将q.out队列清空,所以这里只需要判断q.in队列是否为空即可
class MyStack {
public:
queue<int> q_in;
queue<int> q_out;
MyStack() {
}
void push(int x) {
q_in.push(x);
}
int pop() {
int len=q_in.size();
len--;//提前--,为了保留q_in队列的最后一个元素
while(len){
q_out.push(q_in.front());
q_in.pop();
len--;
}
int res=q_in.front();
q_in.pop();
q_in=q_out;// 再将que2赋值给que1
while(!q_out.empty()){//清空队列q_out
q_out.pop();
}
return res;
}
int top() {
return q_in.back();
}
bool empty() {
return q_in.empty()?true:false;
}
};
方法二,只使用一个队列就可完成以上操作
一个队列在保留最后一个元素时,弹出其余元素的同时将这些元素放到该队列的末尾即可。
class MyStack {
public:
queue<int> q_in;
MyStack() {
}
void push(int x) {
q_in.push(x);
}
int pop() {
int len=q_in.size();
len--;//提前--,为了保留q_in队列的最后一个元素
while(len){
int res=q_in.front();
q_in.pop();
q_in.push(res);
len--;
}
int result=q_in.front();
q_in.pop();
return result;
}
int top() {
return q_in.back();
}
bool empty() {
return q_in.empty()?true:false;
}
};