/**
*
* 两个栈实现队列,实现它的两个函数appendTail和deleteHead
*
*/
public class TwoStackImplQueue {
private Stack<Integer> stack1 = new Stack<Integer>();
private Stack<Integer> stack2 = new Stack<Integer>();
/**
*
* @param num 插入到队尾的数字
*/
public void appendTail(int num){
stack1.push(num);
}
/**
*
* @return 删除的数字,若栈为空则返回null
*/
public Integer deleteHead(){
if(stack1.empty() && stack2.empty()){
return null;
}
//栈不为空则取出元素
if(!stack2.empty()){
return stack2.pop();
}
else{
//将栈1中的元素全部压入栈2
while(!stack1.empty()){
stack2.push(stack1.pop());
}
return stack2.pop();
}
}
public static void main(String[] args) {
TwoStackImplQueue tsiq = new TwoStackImplQueue();
for(int i = 0;i <= 20;i++){
tsiq.appendTail(i);
}
while(true){
Integer num = tsiq.deleteHead();
if(num == null)
break;
System.out.println(num);
}
}
}
两个栈实现队列
最新推荐文章于 2024-02-21 17:10:17 发布