题目:
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.
- 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).
用两个栈来模拟队列,详情的思路请看代码中的注释,对自己无奈的是没有使用Stack这个结构,而是用ArrayList。。。
代码:
class MyQueue {
//用两个栈来模拟一个队列,用ArrayList模拟栈
ArrayList<Integer> stack1 = new ArrayList<Integer>();
ArrayList<Integer> stack2 = new ArrayList<Integer>();
// Push element x to the back of queue.
// 添加元素时就添加到栈1中
public void push(int x) {
stack1.add(x);
}
// Removes the element from in front of queue.
/* 当删除元素时候,就需要用到栈2了
* 若栈2为空,将栈1中的元素逐一弹出再依次压入栈2,这样就保证先入栈的元素位于栈2的栈顶,再栈2的栈顶元素
* 若栈2不为空,则表示栈2中的元素均先于栈1中的元素入栈,因此直接弹出栈2的栈顶元素
*/
public void pop() {
int cur, tmp;
if(!stack2.isEmpty()){
stack2.remove(stack2.size()-1);
}else{
while(!stack1.isEmpty()){
cur = stack1.size()-1;
tmp = stack1.get(cur);
stack1.remove(cur);
stack2.add(tmp);
}
stack2.remove(stack2.size()-1);
}
}
// Get the front element.
// 原理类似于删除元素
public int peek() {
int cur, tmp, val;
if(!stack2.isEmpty()){
val = stack2.get(stack2.size()-1);
}else{
while(!stack1.isEmpty()){
cur = stack1.size()-1;
tmp = stack1.get(cur);
stack1.remove(cur);
stack2.add(tmp);
}
val = stack2.get(stack2.size()-1);
}
return val;
}
// Return whether the queue is empty.
// 只有栈1和栈2都是空的时候才是空
public boolean empty() {
if(stack1.isEmpty() && stack2.isEmpty()){
return true;
}else{
return false;
}
}
}