1 class MyStack { 2 queue<int> q; 3 public: 4 void push(int x) { 5 q.push(x); 6 for (int i=1; i<q.size(); i++) { 7 q.push(q.front()); 8 q.pop(); 9 } 10 } 11 12 int pop() { 13 int i=q.front(); 14 q.pop(); 15 return i; 16 } 17 18 int top() { 19 return q.front(); 20 } 21 22 bool empty() { 23 return q.empty(); 24 } 25 };
用一个队列模拟一个栈,在有新元素进入时,队列转一圈,使其顺序和栈等效。
还有一种方法是用链表来实现
浙公网安备 33010602011771号