剑指offer面试题java实现之题7:用两个栈模拟一个队列的入队和出队操作

剑指offer面试题java实现之题7:用两个栈模拟一个队列的入队和出队操作

import java.util.Stack;
public class QueueWithTwoStacks {
Stack stack1 = new Stack();
Stack stack2 = new Stack();
/**
 * 入队列
 * @param t
 */
public void appendTail(T t){
    stack1.add(t);
}
/**
 * 模拟从对头删除元素
 * @return
 * @throws Exception
 */
public T deleteHead(){
    if(stack2.size()<=0){
        while(stack1.size()>0){//将栈1的所有元素压入栈2中
            T elem = stack1.pop();
            stack2.push(elem);
        }
    }
    if(stack2.size()==0){
        try {
            throw new Exception("队列为空");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return stack2.pop();
}
public static void main(String[] args) {
    QueueWithTwoStacks test  = new         QueueWithTwoStacks();
    test.appendTail("a");
    test.appendTail("b");
    test.appendTail("c");
    }
}

你可能感兴趣的:(算法)