用两个队列实现一个栈的功能?要求给出算法和思路!
<分析>:
入栈:将元素进队列A
出栈:判断队列A中元素的个数是否为1,如果等于1,则出队列,否则将队列A中的元素 以此出队列并放入队列B,直到队列A中的元素留下一个,然后队列A出队列,再把 队列B中的元素出队列以此放入队列A中。
import java.util.LinkedList;
import java.util.Queue;
public class MyStack {
Queue<Integer> queue1 = new LinkedList<Integer>();
Queue<Integer> queue2 = new LinkedList<Integer>();
public void push(int i){
queue1.add(i);
}
public int pop(){
if(queue1.size() == 1){
return queue1.poll();
}else{
while(queue1.size() > 1){
queue2.add(queue1.poll());
}
while(!queue2.isEmpty()){
queue1.add(queue2.poll());
}
return queue1.poll();
}
}
}
public class Test {
public static void main(String[] args){
MyStack stack = new MyStack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
}
}
5
4
3
2
1