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()); } }
本文介绍了一种使用两个栈来实现队列的数据结构方法。通过将元素压入第一个栈,然后将第一个栈中的元素依次弹出并压入第二个栈,从而实现了队列的先进先出特性。当需要获取队列头部元素时,从第二个栈中弹出即可。这种方法巧妙地利用了栈的特性,避免了直接使用队列所带来的复杂性。
358

被折叠的 条评论
为什么被折叠?



