leetcode- 232. 用栈实现队列
相比于用队列实现栈,用栈实现队列能稍微麻烦一点。实现队列时需要两个栈来实现,左边的是出口,右边的是入口。
我们将数据压入right栈,然后出栈保存,进入left,再次出栈的顺序和进入right时的顺序就是一样的。
1.push(x) -- 将一个元素放入队列的尾部。
/** Push element x to the back of queue. */
void push(int x) {
right.push(x);
}
2.pop() -- 从队列首部移除元素。
如果左边有元素,那么首部的元素就是left栈的栈顶,pop掉栈顶的元素就行。
如果左边没有,右边有元素,那么首部的元素就是right底部的元素,将所有的数据交换到left栈之后再pop掉栈顶的元素
如果都没有也是左边栈顶,返回值为空
/** Removes the element from in front of queue and returns that element. */
int pop() {
if(left.empty())
{
while(!right.empty())
{
int data = right.top();
right.pop();
left.push(data);
}
}
int p = left.top();
left.pop();
return p;
}
3.peek() -- 返回队列首部的元素。
如果左边有元素,那么首部的元素就是left栈的栈顶,返回栈顶的元素。
如果左边没有,右边有元素,那么首部的元素就是right底部的元素,将所有的数据交换到left栈之后返回栈顶元素
/** Get the front element. */
int peek() {
if(left.empty())
{
while(!right.empty())
{
int data = right.top();
right.pop();
left.push(data);
}
}
return left.top();
}
4.empty() -- 返回队列是否为空。
/** Returns whether the queue is empty. */
bool empty() {
if(left.empty()&&right.empty())
{
return true;
}
else
return false;
}
完整代码:
class MyQueue {
public:
stack<int> left;
stack<int> right;
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
right.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
if(left.empty())
{
while(!right.empty())
{
int data = right.top();
right.pop();
left.push(data);
}
}
int p = left.top();
left.pop();
return p;
}
/** Get the front element. */
int peek() {
if(left.empty())
{
while(!right.empty())
{
int data = right.top();
right.pop();
left.push(data);
}
}
return left.top();
}
/** Returns whether the queue is empty. */
bool empty() {
if(left.empty()&&right.empty())
{
return true;
}
else
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();
*/