用两个栈实现队列
public class InterView09_ImplementsQueueByStacks {
/*题目描述:用两个栈实现队列,完成出队入队功能,若队列空则返回-1
* 解体思路:
* 声明创建两个栈,stack1(负责入队)、stack2负责出队.
* 元素入队时将其放入stack1中
* 元素出队时从stack2弹出元素,若stack2为空将stack1中的全部元素弹出放入stack2,若stack1也为空返回-1
* */
public static void main(String[] args) {
CQueue queue = new CQueue();
System.out.println(queue.deleteHead());
queue.appendTail(5);
queue.appendTail(2);
System.out.println(queue.deleteHead());
System.out.println(queue.deleteHead());
}
}
class CQueue {
ArrayList<Integer> stack1;
ArrayList<Integer> stack2;
int top1;
int top2;
public CQueue() {
/*初始化过程基于ArrayList创建两个栈
* */
stack1 = new ArrayList<Integer>();
stack2 = new ArrayList<Integer>();
top1=0;
top2=0;
}
public void appendTail(int value) {
/*入队函数
*value放入stack1
* */
stack1.add(top1, value);
top1++;
}
public int deleteHead() {
/*出队函数
*若stack2非空弹出stack2栈顶元素
*若stack2空,stack1全部元素出栈压入stack2,stack2栈顶元素出栈
*若stack2空,stack1空返回-1
* */
if(this.top2 != 0) {
//若stack2非空弹出栈顶元素
top2--;
return stack2.remove(top2);
}else if(this.top2==0 && this.top1 != 0) {
//若stack2空 stack1非空弹出stack1全部元素压入stack2
while(top1 !=0) {
top1--;
int temp = stack1.remove(top1);
stack2.add(top2, temp);
top2++;
}
//弹出stack2的栈顶元素
top2--;
int pop = stack2.remove(top2);
return pop;
}
return -1;
}
}