首先初始化两个栈S1,S2。
入队算法:直接将所有元素压入其中一个栈(S1),over。
出队算法:若S2不为空,S2执行出栈操作,返回栈顶元素。
若S2为空,将S1中的所有元素压入S2,并返回S2的栈顶元素。
下面代码:
package MyCollection;
public class Test01 {
/**
* 用两个栈实现队列
*
* @author ZJ
*
*/
class QueueWithTowStack {
MyStack stack1;
MyStack stack2;
public QueueWithTowStack() {
stack1 = new MyStack();
stack2 = new MyStack();
}
public boolean isEmpty() {// 判断Stack2是否为空,若为空,将stack1压入stack2同时返回true或false.
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.isEmpty();
}
public void enQueue(Object obj) {
stack1.push(obj);
}
public Object deQueue() {
if (!stack2.isEmpty()) {
return stack2.pop();
} else {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}
public static void main(String[] args) {
String[] s1={"111","2222","333"};
Test01 t1 = new Test01();
QueueWithTowStack queueWithTowStack=t1.new QueueWithTowStack();
for (int i = 0; i < s1.length; i++) {
queueWithTowStack.enQueue(s1[i]);
}
queueWithTowStack.isEmpty();
System.out.println(queueWithTowStack.deQueue());
System.out.println(queueWithTowStack.deQueue());
System.out.println(queueWithTowStack.deQueue());
}
111
2222
333