目的:两个栈实现一个队列
1.实现add(),poll(),peek()方法
package com.levin.test.struct;
import java.util.Stack;
public class Stack2Array {
Stack stack_in = new Stack();
Stack stack_out = new Stack();
public void add(Object obj) {
/**
* 1.弹出栈为空;
* 则向插入栈中放数据
* 2.弹出栈和插入栈都不为空;
* 将插入栈的数据全部弹出到插入栈中
*/
if (stack_out.isEmpty()) {
stack_in.push(obj);
} else if (!stack_in.isEmpty() && !stack_out.isEmpty()) {
peekAll(stack_in, stack_out);
peekAll(stack_out, stack_in);
stack_in.push(obj);
} else {
peekAll(stack_out, stack_in);
stack_in.push(obj);
}
}
public void peekAll(Stack source, Stack target) {
while (!source.isEmpty())
{
target.push(source.pop());
}
}
public Object poll() {
if (!stack_in.isEmpty()) {
peekAll(stack_in, stack_out);
}
return stack_out.pop();
}
public Object peek() {
if (!stack_in.isEmpty()) {
peekAll(stack_in, stack_out);
}
return stack_out.peek();
}
public static void main(String[] args) {
Stack2Array stack2Array = new Stack2Array();
for (int i = 1; i <= 3; i++) {
stack2Array.add(i);
}
System.out.println(stack2Array.poll());
stack2Array.add(222);
System.out.println(stack2Array.peek());
}
}