题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
【题目分析】:这个题目其实算是一道简单题,只要有数据结构理论的,完全可以理解整个过程,其核心思想就是两个栈,一个用来push原始进入,类似仓库的功能,仓库的元素按照栈的规则存放入货架,再从货架pop元素就可以了,这个题有一个知识盲点,就是为什么每次执行完就要将元素pop一下,其实就是保证当前循环的正常进行和当前执行原始是新元素。
class Solution
{
public:
void push(int node) {
storage.push(node);
}
int pop() {
int ret;//定义需要pop的元素;
if(shelf.empty()){
while(!storage.empty()){
ret=storage.top();
shelf.push(ret);
storage.pop();
}
}
ret=shelf.top();
shelf.pop();
return ret;
}
private:
stack<int> storage;
stack<int> shelf;
};
LeetCode232leetcode
使用栈来实现队列的如下操作:
- push(x) -- 将一个元素放入队列的尾部。
- pop() -- 从队列首部移除元素。
- peek() -- 返回队列首部的元素。
- empty() -- 返回队列是否为空。
注意:
- 你只能使用标准的栈操作-- 也就是只有
push to top
,peek/pop from top
,size
, 和is empty
操作是可使用的。 - 你所使用的语言也许不支持栈。你可以使用 list 或者 deque (双端队列)来模拟一个栈,只要你仅使用栈的标准操作就可以。
- 假设所有操作都是有效的,比如 pop 或者 peek 操作不会作用于一个空队列上。
class MyQueue {
public:
/** Initialize your data structure here. */
MyQueue() {}
/** Push element x to the back of queue. */
void push(int x) {
sta.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int res;
if(shelf.empty()){
while(!sta.empty()){
res=sta.top();
shelf.push(res);
sta.pop();
}
}
res=shelf.top();
shelf.pop();
return res;
}
/** Get the front element. */
int peek() {
if (shelf.empty()){
while(!sta.empty())
{
int res = sta.top();
shelf.push(res);
sta.pop();}
}
if (!shelf.empty())
{
return shelf.top();
}
}
/** Returns whether the queue is empty. */
bool empty() {
return sta.empty()&&shelf.empty();
}
private:
stack<int> sta;
stack<int> shelf;
};