题目入口: 用两个栈实现队列https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof/
使用双栈,stack1用于增数据,stack2用于删数据,stack2删数据的时候,首先判断自己是否为空,如果不为空,则栈内有数据,此时stack2中的数据必定会比stack1进来的早,因为这些数据是之前从stack1搬到stack2的,stack2如果没数据,需要把stack1中的数据搬到stack2中,因为栈是先进后出,所以数据从stack1移到stack2时,stack1中栈底的数据(最旧的数据)会在stack2的栈顶,此时取出stack2栈顶的数据即可.
class CQueue { private Stack<Integer> stack1 = null; private Stack<Integer> stack2 = null; public CQueue() { stack1 = new Stack(); stack2 = new Stack(); } public void appendTail(int value) { stack1.push(value); } public int deleteHead() { if(stack2.isEmpty()){ while(!stack1.isEmpty()){ stack2.push(stack1.pop()); } } return stack2.isEmpty()?-1:stack2.pop(); } }