用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
方法一:
class CQueue {
Stack<Integer> stack1,stack2;
public CQueue() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}
public void appendTail(int value) {
stack1.push(value);
}
public int deleteHead() {
if(stack2.isEmpty()){
while (!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
if(stack2.isEmpty()){
return -1;
}else {
int deleteItem = stack2.pop();
return deleteItem;
}
}
}
方法二:
class CQueue {
LinkedList<Integer> linkedList1,linkedList2;
public CQueue() {
linkedList1 = new LinkedList<>();
linkedList2 = new LinkedList<>();
}
public void appendTail(int value) {
linkedList1.add(value);
}
public int deleteHead() {
if(linkedList2.isEmpty()){
while (!linkedList1.isEmpty()){
linkedList2.add(linkedList1.removeLast());
}
}
if(linkedList2.isEmpty()){
return -1;
}else {
int deleteItem = linkedList2.removeLast();
return deleteItem;
}
}
}