本文最后更新于 2024年5月31日 上午
此帖仅作打卡用,过于简单,建议跳过 # 232.用栈实现队列
根据题意,用俩栈来回倒就行
code
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 MyQueue { public: stack<int> q1; stack<int> q2; MyQueue() {} void push(int x) { while(!q2.empty()){ int pipe = q2.top(); q2.pop(); q1.push(pipe); } q1.push(x); } int pop() { while(!q1.empty()){ int pipe = q1.top(); q1.pop(); q2.push(pipe); } int ans = q2.top(); q2.pop(); return ans; } int peek() { while(!q1.empty()) { int pipe = q1.top(); q1.pop(); q2.push(pipe); } return q2.top(); } bool empty() { return q1.empty() && q2.empty(); } };
|
一个双端队列完事
code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class MyStack { public: deque<int> d1; MyStack() {} void push(int x) { d1.push_front(x); } int pop() { int p = d1.front(); d1.pop_front(); return p; } int top() { return d1.front(); } bool empty() { return d1.empty(); } };
|