题目内容
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:
1. You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid.
2. 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.
3. You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
题目分析
通过栈实现队列的操作。
在这里通过栈列实现队列的操作。队列的特点:先进先出。 栈的特点,后进先出。
通过两个栈来实现,栈s1和栈s2。
在s1中将所有的元素push进去,然后pop出来存入s2中,即可实现队列操作。
代码如下
class MyQueue {
Stack<Integer> s1 = new Stack<>();
Stack<Integer> s2 = new Stack<>();
// 队列的push操作
public void push(int x) {
s1.push(x);
}
// 队列的poo操作,检测s2是否为空,不为空则直接pop,为空则讲s1中的元素push进入s2
public void pop() {
if(!s2.isEmpty())
s2.pop();
else
{
while(!s1.isEmpty())
{
s2.push(s1.pop());
}
s2.pop();
}
}
// 队列最前元素
public int peek() {
if(!s2.isEmpty())
return s2.peek();
else
{
while(!s1.isEmpty())
{
s2.push(s1.pop());
}
}
return s2.peek();
}
// 判断是否为空
public boolean empty() {
if(s1.isEmpty()&&s2.isEmpty())
return true;
return false;
}
}