leetcode链接:
232. 用栈实现队列
class MyQueue {
private Stack<Integer> head;
private Stack<Integer> tail;
public MyQueue() {
head = new Stack<Integer>();
tail = new Stack<Integer>();
}
public void push(int x) {
//push的时候将元素push到队尾tail
tail.push(x);
}
public int pop() {
//pop的时候注意:当head有元素时,直接pop队头head中的元素即可;否则,将tail依次push到head中,再弹出head中的元素
if(head.isEmpty()){
while(!tail.isEmpty()){
head.push(tail.pop());
}
}
return head.pop();
}
public int peek() {
//peek的时候同pop一样,如果队头head中有元素,直接返回head中的元素即可;否则将tail依次push到head中,再返回head中的元素
if(head.isEmpty()){
while(!tail.isEmpty()){
head.push(tail.pop());
}
}
return head.peek();
}
public boolean empty() {
return tail.isEmpty() && head.isEmpty();
}
}
/**
* 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();
* boolean param_4 = obj.empty();
*/
class CQueue {
private Stack<Integer> head;
private Stack<Integer> tail;
public CQueue() {
head = new Stack<Integer>();
tail = new Stack<Integer>();
}
public void appendTail(int value) {
tail.push(value);
}
public int deleteHead() {
int result;
//比上面增加了一种情况
if(head.isEmpty() && tail.isEmpty()){
result = -1;
}else if(head.isEmpty()){
while(!tail.isEmpty()){
head.push(tail.pop());
}
result = head.pop();
}else{
result = head.pop();
}
return result;
}
}
/**
* Your CQueue object will be instantiated and called as such:
* CQueue obj = new CQueue();
* obj.appendTail(value);
* int param_2 = obj.deleteHead();
*/