☰
LeetCode.232.用栈实现队列
2026/9/29 21:15:00 网站建设 项目流程

题目

请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(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(双端队列)来模拟一个栈,只要是标准的栈操作即可。

本题主要先用来熟悉这些push、pop、top等操作的用法,用栈实现队列还是好理解的。

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 result = stOut.top(); stOut.pop(); return result; } int peek() { int res = this->pop();//使用已有的pop函数 stOut.push(res); //出栈再入栈 return res; } bool empty() { if (stOut.empty() && stIn.empty()) { return true; } return false; } }; /** * 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(); */

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询