用两个栈实现队列,剑指offer P59
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用两个栈实现队列,剑指offer P59相关的知识,希望对你有一定的参考价值。
public class QueueByStack { private Stack<Integer> stack1; private Stack<Integer> stack2; public QueueByStack() { // TODO Auto-generated constructor stub stack1 = new Stack<Integer>(); stack2 = new Stack<Integer>(); } public void appendTail(Integer a) { stack1.push(a); } public Integer deleteHead() throws Exception{ if(stack2.isEmpty()) { while(!stack1.isEmpty()) { stack2.push(stack1.pop()); } } if(stack2.isEmpty()) { throw new Exception("队列为空,不能删除"); } return stack2.pop(); } public static void main(String[] args) throws Exception { new QueueByStack(); QueueByStack ququeByStack = new QueueByStack(); ququeByStack.appendTail(1); ququeByStack.appendTail(2); System.out.println(ququeByStack.deleteHead()); } }
以上是关于用两个栈实现队列,剑指offer P59的主要内容,如果未能解决你的问题,请参考以下文章