用队列实现栈
class MyStack {
public:
MyStack() {
}
queue<int> q1,q2;
void push(int x) {
q1.push(x);
}
int pop() {
while(q1.size()>1){
q2.push(q1.front());
q1.pop();
}
int a = q1.front();
q1 = q2;
while(!q2.empty()){
q2.pop();
}
return a;
}
int top() {
return q1.back();
}
bool empty() {
return q1.empty();
}
};
用栈实现队列
class MyQueue {
public:
MyQueue() {
}
stack<int>s1,s2;
void push(int x) {
s1.push(x);
}
int pop() {
if(s2.empty()){
while(!s1.empty()){
s2.push(s1.top());
s1.pop();
}
}
int a = s2.top();
s2.pop();
return a;
}
int peek() {
if(s2.empty()){
while(!s1.empty()){
s2.push(s1.top());
s1.pop();
}
}
int a = s2.top();
return a;
}
bool empty() {
return s1.empty()&&s2.empty();
}
};
本文介绍如何使用队列实现栈的功能,以及如何利用栈来实现队列的行为。通过两个具体的类实现,展示了数据结构转换的基本原理。

被折叠的 条评论
为什么被折叠?



