leetcode-232-Implement Queue using Stacks
题目描述:
Implement the following operations of a queue using stacks.
- push(x) -- Push element x to the back of queue.
- pop() -- Removes the element from in front of queue.
- peek() -- Get the front element.
- empty() -- Return whether the queue is empty.
Notes:
- You must use only standard operations of a stack -- which means only
push to top
,peek/pop from top
,size
, andis empty
operations are valid. - Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
- You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
要完成的函数:
void push(int x)
int pop() //返回队首元素值并且删去该值
int peek()
bool empty()
说明:
1、这道题要求使用堆栈来实现队列,只能使用堆栈的push pop top size empty的功能,来完成队列的压入、弹出、读取队首元素、判断队列是否为空的函数。
2、队列跟堆栈的唯一不同之处,在于队列是队尾输入、队首输出,堆栈是队尾输入、队尾输出。堆栈其实也是一个特殊的队列。
所以我们可以每次压入新元素,都把新元素放到堆栈的底部,而始终保持最先压入的元素在堆栈顶部,这样我们的后续步骤,比如删除或者读取队首元素,也就变得异常简单了。
而完成新元素在堆栈底部,最先压入的元素在堆栈顶部,我们需要一个辅助堆栈来实现。
代码如下:(附详解)
stack<int>stack1;//主堆栈
stack<int>stack2;//辅助堆栈
/** Push element x to the back of queue. */
void push(int x)
{
while(!stack1.empty())//在压入新元素之前,把所有已有元素取出来,放在辅助堆栈中。辅助堆栈中元素的顺序是,较旧的元素在底,较新的元素在顶。
{
stack2.push(stack1.top());
stack1.pop();
}
stack1.push(x);//压入新元素在最底部
while(!stack2.empty())//新元素压入后,把辅助堆栈中的元素拿出来,压入主堆栈中,保持较新元素在底,较旧元素在顶
{
stack1.push(stack2.top());
stack2.pop();
}
}
/** Removes the element from in front of queue and returns that element. */
int pop()
{
int t=stack1.top();
stack1.pop();
return t;
}
/** Get the front element. */
int peek()
{
return stack1.top();
}
/** Returns whether the queue is empty. */
bool empty()
{
return stack1.empty();
}
上述代码实测2ms,beats 100% of cpp submissions。