栈和队列互相实现
作者:
阿飞大魔王
,
2024-07-28 21:39:47
,
所有人可见
,
阅读 9
用两个栈实现队列
class MyQueue {
private:
stack<int>in,out;
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
in.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
if(out.empty())
{
while(!in.empty())
{
out.push(in.top());
in.pop();
}
}
int res=out.top();
out.pop();
return res;
}
/** Get the front element. */
int peek() {
if(out.empty())
{
while(!in.empty())
{
out.push(in.top());
in.pop();
}
}
return out.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return in.empty()&&out.empty();
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* bool param_4 = obj.empty();
*/
用队列实现栈
法一 两个队列
class MyStack {
private:
queue<int>q1,q2;
public:
MyStack() {
}
void push(int x) {
q2.push(x);
while(!q1.empty())
{
q2.push(q1.front());
q1.pop();
}
swap(q1,q2);
}
int pop() {
int res=q1.front();
q1.pop();
return res;
}
int top() {
return q1.front();
}
bool empty() {
return q1.empty();
}
};
法二 一个队列
class MyStack {
private:
queue<int>q;
public:
MyStack() {
}
void push(int x) {
int count=q.size();
q.push(x);
while(count--)
{
int t=q.front();
q.pop();
q.push(t);
}
}
int pop() {
int res=q.front();
q.pop();
return res;
}
int top() {
return q.front();
}
bool empty() {
return q.empty();
}
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/