两个队列实现栈&两个栈实现队列(JAVA)

1,两个栈实现队列

  

  题目描述

  用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
  
  思路:栈的特点时先进后出,队列的特点是先进先出。
  若此时有两个队列stack1,stack2,我们用stack1来存储入队的元素,而用stcak2来辅助进行pop()操作。
  
    public  void push(int node) {
        stack1.push(node);
    }

  对于pop操作,我需要先进入的元素先出来,若stcak1中按顺序存放着ABC,将其依次pop出来,放入stcak2中,就变成了CBA,此时再让stack2pop()出来元素,就满足了队列的要求。

  具体操作:

  1,看辅助栈stack2中是否还有元素,若有,直接pop出来,若没有,观察stack1中元素个数

  2,若stack1中元素个数>0,则将stack1中的元素一次pop,并push进stack2中。

  

    public int pop() {
        if(stack2.isEmpty()){
            while(!stack1.isEmpty()){
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }

2,两个队列实现栈

  思路:若此时有两个队列q1和q2。此时,任意选一个队列当作入栈队列,比如先拿q1来入栈,若入栈了ABC ,若此时想进行出栈操作,则将q1中元素一次出队列至q1中,直至q1中只剩一个元素,此时即C元素。然后将q1中剩的最后一个元素出队列返回。之后,若再此进行入栈操作时,就选择q1和q2中非空队列进行入栈。

   关键点:将一个队列出队进入另一个队列,直至剩下一个元素。

    

 1     Queue<Integer> queue1 = new LinkedList<>();
 2     Queue<Integer> queue2 = new LinkedList<>();
 3 
 4     public void push(int node){
 5         if(!queue1.isEmpty()){
 6             queue1.offer(node);
 7         }else {
 8             queue2.offer(node);
 9         }
10     }
11 
12     public Integer  pop(){
13         if(queue1.isEmpty()&&queue2.isEmpty())
14             return null;
15         if(queue1.isEmpty()){
16             while(queue2.size()>1){
17                 queue1.offer(queue2.poll());
18             }
19             return queue2.poll();
20         }
21         //(queue2.isEmpty())
22         while(queue1.size()>1){
23             queue2.offer(queue1.poll());
24         }
25         return queue1.poll();
26     }

  

原文地址:https://www.cnblogs.com/ztqup666/p/9233506.html