/**
* 用两个栈实现队列
* 入队时 offer():向栈1压栈
* 出队时 poll():
* 1 将栈1的元素全部出栈
* 2 将出栈的元素按出栈顺序压入栈2
* 3 栈2出栈(并作为返回值)
* 4 将栈2的元素去全部出栈
* 5 按出栈顺序将元素压入栈1
* 空判断 empty():判断栈1是否为空
*
* 效率测试(出队时队列中有100000条元素)
* 次数: 1 10 100 1000 10000 100000 1000000
* 入队时间: 1 1 3 14 63
* 出队时间:44 271 2292 21666
*
* 队列中有1000条数据时测试出入队(一入一出为一次)
* 次数: 10 100 1000
* 时间: 11 54 273
*
* 结果:出队效率太低
* @author
* @version 0.1
*/
public class MyQueue {
private Stack<Integer> stack1;
private Stack<Integer> stack2;
public MyQueue(){
stack1 = new Stack<Integer>();
stack2 = new Stack<Integer>();
}
public int offer(int o){
stack1.push(o);
return o;
}
public int poll(){
while(!stack1.empty()){
stack2.push(stack1.pop());
}
Integer po = stack2.pop();
while (!stack2.empty()){
stack1.push(stack2.pop());
}
return po;
}
public boolean empty(){
return stack1.empty();
}
public static void main(String[] args) {
MyQueue queue = new MyQueue();
List<Integer> list = new ArrayList<Integer>();
queue.offer(1);
queue.offer(2);
queue.offer(3);
queue.offer(4);
queue.offer(5);
while (!queue.empty()){
list.add(queue.poll());
}
System.out.println(list);
}
}
运行结果:
[1, 2, 3, 4, 5]
/**
* 用两个栈实现队列
* 入队时 offer():判断队列是否为空 是--stack1压栈
* 否--判断stack1是否为空
* 是--stack2出栈并将出栈元素压入stack1,再压栈
* 否--stack1压栈
* 出队时 poll():判断队列是否为空 是--抛出异常
* 否:判断stack2是否为空
* 是--stack1出栈,并将元素压入stack2,stack2出栈
* 否--stack2出栈
* 空判断 empty():判断stack1和stack2是否同时为空
*
* 效率测试(出队时队列中有100000条元素)
* 次数: 1 10 100 1000 10000 100000 1000000
* 入队时间: 1 1 3 14 65
* 出队时间:24 24 26 27 31 50
*
* 队列中有1000条数据时测试出入队(一入一出为一次)
* 次数: 10 100 1000
* 时间: 12 56 276
* 结果:出队效率明显提升
* @author
* @version 0.1
*/
public class MyQueue {
private Stack<Integer> stack1;
private Stack<Integer> stack2;
public MyQueue(){
stack1 = new Stack<Integer>();
stack2 = new Stack<Integer>();
}
public int offer(int o){
//判断队列是否为空 是--stack1压栈
// 否--判断stack1是否为空
// 是--stack2出栈并将出栈元素压入stack1,再压栈
// 否--stack1压栈
if(!this.empty() && this.stack1.empty()){
while (!this.stack2.empty()){
this.stack1.push(this.stack2.pop());
}
}
this.stack1.push(o);
return o;
}
public int poll(){
Integer po;
//判断队列是否为空 是--抛出异常
// 否:判断stack2是否为空
// 是--stack1出栈,并将元素压入stack2,stack2出栈
// 否--stack2出栈
if(!this.empty()){
if(this.stack2.empty()){
while (!this.stack1.empty()){
this.stack2.push(this.stack1.pop());
}
}
po = this.stack2.pop();
}else {
throw new EmptyStackException();
}
return po;
}
public boolean empty(){
return (stack1.empty()) && (stack2.empty());
}
public static void main(String[] args) {
MyQueue queue = new MyQueue();
List<Integer> list = new ArrayList<Integer>();
queue.offer(1);
queue.offer(2);
queue.offer(3);
queue.offer(4);
queue.offer(5);
while (!queue.empty()){
list.add(queue.poll());
}
System.out.println(list);
}
}
运行结果:
[1, 2, 3, 4, 5]