栈与队列part01
用栈实现队列
时间复杂度: push和empty为O(1), pop和peek为O(n)
空间复杂度: O(n)
class MyQueue {
public:stack<int> stIn; // 输入栈stack<int> stOut; // 输出栈MyQueue() {}void push(int x) {stIn.push(x);}int pop() {// 只有当输出栈为空时,才从输入栈里导入全部数据if(stOut.empty()) {while(!stIn.empty()) {stOut.push(stIn.top());stIn.pop();}}int res = stOut.top();stOut.pop();return res;}int peek() {int res = this->pop();stOut.push(res); // pop函数弹出了res,所以再添加回去return res;}bool empty() {return stIn.empty() && stOut.empty();}
};/*** Your MyQueue object will be instantiated and called as such:* MyQueue* obj = new MyQueue();* obj->push(x);* int param_2 = obj->pop();* int param_3 = obj->peek();* bool param_4 = obj->empty();*/
用队列实现栈
时间复杂度: pop为O(n),其他为O(1)
空间复杂度: O(n)
class MyStack {
public:queue<int> que;MyStack() {}void push(int x) {que.push(x);}int pop() {int size = que.size();size--;// 将队列的头部元素(除最后一个元素外),重新添加到队列的尾部while(size--) { que.push(que.front());que.pop();}int res = que.front();que.pop();return res;}int top() {return que.back();}bool empty() {return que.empty();}
};/*** Your MyStack object will be instantiated and called as such:* MyStack* obj = new MyStack();* obj->push(x);* int param_2 = obj->pop();* int param_3 = obj->top();* bool param_4 = obj->empty();*/