两个栈实现队列
//直接插入到st1中去就可以。
void push(stack<int> *st1,int key){
st1.push(key);
}
//st2为空则把st1中的元素全部放到st1中,并且弹出st2.pop(); 若st2不为空则直接弹出
void pop(stack<int> *st1, stack<int> *st2){
if(st2.empty()){
while(!st1.empty()){
st2.push(st1.top());
st1.pop();
}
}
if(st2.empty()){
cout<<"没有元素了"<<endl;
return;
}
st2.pop();
}
两个队列实现栈
class Stack { public: // Push element x onto stack. void push(int x) { if (!q1.empty()) { q2.push(x); while (!q1.empty()) { q2.push(q1.front()); q1.pop(); } } else { q1.push(x); while (!q2.empty()) { q1.push(q2.front()); q2.pop(); } } } // Removes the element on top of the stack. void pop() { if (q1.empty()&&q2.empty()) throw new exception("stack is empty"); else if (!q1.empty()) q1.pop(); else q2.pop(); } // Get the top element. int top() { if (!q1.empty()) return q1.front(); else return q2.front(); } // Return whether the stack is empty. bool empty() { return (q1.empty()&&q2.empty()); } private: queue<int> q1, q2; };
