剑指offer,Java版第七题:用两个栈实现一个队列。队列的声明如下,请实现它的两个函数appendTail和deleteHead, 分别完成在队列尾部插入结点和在队列头部删除结点的功能。

/*

用两个栈实现一个队列。队列的声明如下,请实现它的两个函数appendTail和deleteHead,

分别完成在队列尾部插入结点和在队列头部删除结点的功能。

*/

import java.util.*;

public class Class8 {

static class stackToQueue{

Stack<Integer> stack1 = new Stack<Integer>();

Stack<Integer> stack2 = new Stack<Integer>();

public void appendTail(int a){

stack1.push(a);

}

public int deleteHead(){

if(stack2.empty()){

if(stack1.empty()){

throw new RuntimeException("队列为空!");

}

else{

while(!stack1.empty()){

stack2.push(stack1.pop());

}

}

}

if(stack2.empty()){

if(stack1.empty()){

if(stack1.empty()){

throw new RuntimeException("队列操作存在错误!");

}

else{

while(!stack1.empty()){

stack2.push(stack1.pop());

}

}

}

}

return stack2.pop();

}

}

public void test() {

stackToQueue stq= new stackToQueue();

stq.appendTail(1);

stq.appendTail(2);

System.out.println(stq.deleteHead());

stq.appendTail(3);

System.out.println(stq.deleteHead());

System.out.println(stq.deleteHead());

}

public static void main(String[] args) {

// TODO Auto-generated method stub

Class8 c = new Class8();

c.test();

}

}