用两个栈实现队列(非转载)
就是酱紫:
#include<iostream> #include<stack> using namespace std; struct my_queue { stack<int> s1, s2; }; void enqueue(my_queue &q, int value) { q.s1.push(value); } int dequeue(my_queue &q) { if(q.s2.empty()) { while(!q.s1.empty()) { q.s2.push(q.s1.top()); q.s1.pop(); } } if(q.s2.empty()) { cerr << "The queue is empty/n"; exit(1); } int temp = q.s2.top(); q.s2.pop(); return temp; } int main() { my_queue q; enqueue(q,1); enqueue(q,2); cout << dequeue(q)<<endl; }