
题目描述:
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型
解题思路:
时间复杂度: $O(n)$, 空间复杂度: $O(n)$.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
class {
public: void push(int node) { while(!s2.empty()) { s1.push(s2.top()); s2.pop(); } s2.push(node); while(!s1.empty()) { s2.push(s1.top()); s1.pop(); } } int pop() { int x; x = s2.top(); s2.pop(); return x; }
private: stack<int> s1; stack<int> s2; };
|
近期评论