题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
 
题目链接:

 

特性:

栈(stack):后进先出

队列(queue):先进先出

 

分析:

ABC  ->  CBA  ->  ABC

所以走两次栈即可

 

 

 

 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         while(!stack2.empty()){
13             return stack2.pop();
14         }
15         while(!stack1.empty()){
16             stack2.push(stack1.pop());
17         }
18         while(!stack2.empty()){
19             return stack2.pop();
20         }
21         return 0;
22     }
23 }

 

 

 

变形题:

用两个队列模拟栈

 

分析:

ABC -> ABC -> ABC

所以走多次队列行不通,但可以看出每次换队列顺序是不变的,所以需要最一开始就改变顺序。

关键点是push这个操作,每次push时,先将这次push的值压入队列2,再将队列1压入队列2,从而改变顺序;

起始状态:q1:    ,q2:

插入A元素

1、A->q2,q1->q2。 终态:q1:   .,q2:A

2、q1: A ,q2:

插入B元素

1、B->q2,  q1->q2。终态:q1:   ,q2:BA

2、 q1: BA  ,q2:

 

代码:

 1 package com.sunshine.aaa;
 2 
 3 import org.junit.Test;
 4 
 5 import java.util.LinkedList;
 6 import java.util.Queue;
 7 
 8 public class queueMoNistack {
 9     private Queue<Integer> q1=new LinkedList<>();
10     private Queue<Integer> q2=new LinkedList<>();
11     
12 
13     @Test
14     public void test(){
15         push(1);
16         push(2);
17         push(3);
18         System.out.println(pop());
19         System.out.println(pop());
20         System.out.println(pop());
21     }
22 
23     public void push(int a){
24         q2.add(a);
25         while(!q1.isEmpty()){
26             q2.add(q1.poll());
27         }
28         while(!q2.isEmpty()){
29             q1.add(q2.poll());
30         }
31     }
32     public int pop(){
33         if(!q1.isEmpty()){
34             return q1.poll();
35         }
36         return 0;
37     }
38 }