💫学一点也是学,不要停止学习。
📆学习日期:2025年3月14日18:59:47
💻学习内容:栈与队列理论基础 | 用栈实现队列
⏲️学习时长:1h10min
练习题目-用栈实现队列
题目描述
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push
、pop
、peek
、empty
):
实现 MyQueue
类:
void push(int x)
将元素 x 推到队列的末尾int pop()
从队列的开头移除并返回元素int peek()
返回队列开头的元素boolean empty()
如果队列为空,返回true
;否则,返回false
说明:
- 你 只能 使用标准的栈操作 —— 也就是只有
push to top
,peek/pop from top
,size
, 和is empty
操作是合法的。 - 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
示例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
解题思路
- 整体思路&&注意事项
- 没有什么具体的算法,考察对栈和队列的理解。利用栈 模拟 队列的行为
- 需要使用两个栈才可以实现队列
stack_in
/stack_out
- 代码实现
push()
函数:stack_in.push()
pop()
函数:判断stack_out
是否为空,将stack_in
中的元素全部push到stack_out
中,再从stack_out
出栈peek()
函数:判断出栈是否为空,将stack_in
中的元素全部push到stack_out
中,再获取栈顶元素。/ 利用this->
指针复用函数pop()
,由于pop函数执行了弹出操作,因此需要再将result进行push操作。
Bug
class MyQueue {
public:
stack<int> stIn;//入栈
stack<int> stOut;//出栈
//初始化队列
MyQueue() {
}
//入队
void push(int x) {
stIn.push(x);
}
//出队,并返回此元素
int pop() {
//当stOut为空时,从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();//函数复用
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(1)。对于每个元素,至多入栈和出栈各两次,故均摊复杂度为 O(1)。
空间复杂度:O(n)。其中 n 是操作总数。对于有 n 次 push 操作的情况,队列中会有 n 个元素,故空间复杂度为 O(n)。
作者:力扣官方题解
学习总结
int res=this->pop();//函数复用
使用this
指针复用 类函数
相关题目
用队列实现栈 简单