思路:
- 插入的时候,直接把内容插入
sta1中即可 - 弹出的时候,分成两种情况。
1.如果sta2空了,那么如果sta1同时空了,那么就说明全弹完了,返回-1;否则,就是第一次弹栈,那么需要把sta1的内容全部倒进sta2当中(反了两次就正了)
2.如果非空,那么就说明不是第一次弹栈,第一次弹栈的时候已经反过一次了,所以正常弹出即可。
代码:
class CQueue {public: stack<int> sta1, sta2; CQueue() { ; } void appendTail(int value) { sta1.push(value); } int deleteHead() { // 2种情况可能触发:1.第一次执行 2.sta2弹光了 if (sta2.empty()) { // 如果两个栈都空了 if (sta1.empty()) { return -1; } // 把sta1的内容倒进去 while (!sta1.empty()) { sta2.push(sta1.top()); sta1.pop(); } } int num = sta2.top(); sta2.pop(); return num; }};/** * Your CQueue object will be instantiated and called as such: * CQueue* obj = new CQueue(); * obj->appendTail(value); * int param_2 = obj->deleteHead(); */