栈和队列的互相实现
两个栈实现队列
两个栈,一个尾端压入,一个头端弹出
- 压入时,都压到一个栈里面
- 只有当弹出栈空了时,才将压入栈里面的元素都转到弹出栈中。
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
if(stack2.empty())
{
while(!stack1.empty())
{
int temp = stack1.top();
stack2.push(temp);
stack1.pop();
}
}
if(stack2.empty()) return 0;
int top = stack2.top();
stack2.pop();
return top;
}
private:
stack<int> stack1;
stack<int> stack2;
};
两个队列实现栈
实现上 没有两个栈做队列那么优雅。
- 一个队列push,保持只有一个队列有元素
- pop时,将有元素的那个队列除了最后一个元素,都转到另一个队列,把剩余的一个元素pop
#pragma once
#include <queue>
#include <iostream>
using namespace std;
class MyStack
{
public:
int pop();
void push(int val);
friend ostream& operator<<(ostream& os, MyStack& obj);
private:
queue<int> que1;
queue<int> que2;
};
inline int MyStack::pop()
{
int popval = 0;
queue<int> *pQueValid;
queue<int> *pQueWait;
if (que1.empty())
{
pQueValid = &que2;
pQueWait = &que1;
}
else
{
pQueValid = &que1;
pQueWait = &que2;
}
if (pQueValid->empty()) return 0;
int size = pQueValid->size();
for (int i = 0; i < size - 1; ++i)
{
pQueWait->push(pQueValid->front());
pQueValid->pop();
}
popval = pQueValid->front();
pQueValid->pop();
return popval;
}
inline void MyStack::push(int val)
{
if (que1.empty())
que2.push(val);
else
que1.push(val);
cout << "push: " << val << endl;
}
ostream & operator<<(ostream & os, MyStack & obj)
{
os << "que1:";
queue<int> t1(obj.que1);
while (!t1.empty())
{
os << t1.front();
t1.pop();
}
os << endl;
os << "que2:";
queue<int> t2(obj.que2);
while (!t2.empty())
{
os << t2.front();
t2.pop();
}
os << endl;
return os;
}
测试
#include "MyStack.h"
#include <iostream>
using namespace std;
int main()
{
MyStack stack;
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
//cout << stack << endl;
cout << stack.pop() << endl;
cout << stack.pop() << endl;
stack.push(6);
cout << stack.pop() << endl;
cout << stack.pop() << endl;
cout << stack.pop() << endl;
cout << stack.pop() << endl;
stack.push(2);
stack.push(3);
cout << stack.pop() << endl;
cout << stack.pop() << endl;
cout << stack.pop() << endl;
cout << stack.pop() << endl;
system("pause");
return 0;
}