标签:value pop 出栈 push turn return val head 入栈
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead?操作返回 -1 )
一个入栈,一个出栈
java的Stack pop方法会返回出栈的值。
class CQueue {
Stack<Integer> appendTailStack;
Stack<Integer> deleteHeadStack;
public CQueue() {
//负责队末插入的栈
appendTailStack =new Stack<>();
//出队的栈
deleteHeadStack = new Stack<>();
//平时存放在出队栈中,顺序如同队列
}
public void appendTail(int value) {
if (deleteHeadStack.empty()) appendTailStack.push(value);
else
{ //先把队push进appendTail栈
while(!deleteHeadStack.empty()){
appendTailStack.push(deleteHeadStack.pop());
}
//插入
appendTailStack.push(value);}
//倒回去
while(!appendTailStack.empty()){
deleteHeadStack.push(appendTailStack.pop());
}
}
public int deleteHead() {
if(deleteHeadStack.empty()) return -1;
int head = deleteHeadStack.pop();;
return head;
}
}
标签:value pop 出栈 push turn return val head 入栈
原文地址:https://www.cnblogs.com/Jun10ng/p/12345379.html