232.用栈实现队列
题目链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
视频讲解:栈的基本操作! | LeetCode:232.用栈实现队列_哔哩哔哩_bilibili
文章讲解:代码随想录
【思路】
两个栈:一个输入栈,一个输出栈
class MyQueue {
public:
stack<int> stIn;
stack<int> stOut;
MyQueue() {
}
void push(int x) {
stIn.push(x);
}
int pop() {
// 只有当stOut为空的时候,再从stIn里导入数据(导入stIn全部数据)
if (stOut.empty()) {
// 从stIn导入数据直到stIn为空
while(!stIn.empty()) {
stOut.push(stIn.top());
stIn.pop();
}
}
int result = stOut.top();
stOut.pop();
return result;
}
int peek() {
int res = this->pop(); // 直接使用已有的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();
*/
- 时间复杂度: push和empty为O(1), pop和peek为O(n)
- 空间复杂度: O(n)
225. 用队列实现栈
题目链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
视频讲解:队列的基本操作! | LeetCode:225. 用队列实现栈_哔哩哔哩_bilibili
文章讲解:代码随想录
class MyStack {
public:
queue<int> que;
MyStack() {
}
void push(int x) {
que.push(x);
}
int pop() {
int len = que.size();
len--;
while(len--){
que.push(que.front());
que.pop();
}
int result = que.front();
que.pop();
return result;
}
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();
*/
- 时间复杂度: pop为O(n),其他为O(1)
- 空间复杂度: O(n)