用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
用两个栈实现一个队列的功能?要求给出算法和思路!
<分析>:
入队:将元素进栈A
出队:判断栈B是否为空,如果为空,则将栈A中所有元素pop,并push进栈B,栈B出栈;
如果不为空,栈B直接出栈。
1 import java.util.Stack; 2 3 public class Solution { 4 Stack<Integer> stack1 = new Stack<Integer>(); 5 Stack<Integer> stack2 = new Stack<Integer>(); 6 7 public void push(int node) { 8 stack1.push(node); 9 } 10 11 public int pop() { 12 if(stack1.empty()&&stack2.empty()){ 13 throw new RuntimeException("Queue is empty!"); 14 } 15 if(stack2.empty()){ 16 while(!stack1.empty()){ 17 stack2.push(stack1.pop()); 18 } 19 } 20 return stack2.pop(); 21 } 22 }
用两个队列实现一个栈的功能?要求给出算法和思路!
<分析>:
入栈:将元素进队列A
出栈:判断队列A中元素的个数是否为1,如果等于1,则出队列,否则将队列A中的元素依次出队列并放入队列B,直到队列A中的元素留下一个,然后队列A出队列,再把队列B中的元素出队列以此放入队列A中。