用栈实现队列

用栈来模拟一个队列,要求实现队列的基本操作:入队、出队

 
思路:  队列: 先进先出,:先进后出;
  • 要想栈实现先进先出,那么用一个栈肯定不行,需要2个栈配合操作。一个栈用来作为入口,另一个栈作为出口。
  • 栈A的元素需要按入栈的顺序出栈,那么将A中的元素逐个pop,并将这些元素逐个在push到栈B中,然后再通过B来pop。(可以手动画下这个过程)
  • 只要有元素入栈,都是用A来push,出栈的话,都是将A的元素pop到B中,然后B再pop。
代码实现:
 1 import java.util.ArrayList;
 2 import java.util.List;
 3 import java.util.Stack;
 4 
 5 /**
 6  * 用栈来模拟一个队列,要求实现队列的基本操作:入队、出队
 7  */
 8 
 9 public class QueueByStack {
10     private Stack<Integer> stack1 = new Stack<>();
11     private Stack<Integer> stack2 = new Stack<>();
12 
13     public void push(int element){
14         stack1.push(element);
15     }
16 
17     public void pop(){
18         List<Integer> elements = new ArrayList<>();
19         while (!stack1.isEmpty()){
20             stack2.push(stack1.pop());
21         }
22         while (!stack2.isEmpty()){
23             System.out.println("pop: " +  stack2.pop());
24         }
25 
26     }
27 
28     public List<Integer> getStackElement(){
29         List<Integer> elementList = new ArrayList<>();
30         for (int i=0; i<stack1.size(); i++){
31             elementList.add(stack1.get(i));
32         }
33         return elementList;
34     }
35     public static void main(String[] args){
36         QueueByStack stack = new QueueByStack();
37         System.out.println("==== Push ==== ");
38         stack.push(4);
39         System.out.println("push: 4");
40         stack.push(9);
41         System.out.println("push: 9");
42         stack.push(7);
43         System.out.println("push: 7");
44 
45         System.out.println("Push result: " + stack.getStackElement().toString());
46         while (!stack.stack1.isEmpty()){
47             System.out.println( "pop: " + stack.stack1.pop());
48         }
49         System.out.println();
50         System.out.println("==== Push Aagin ==== ");
51         stack.push(4);
52         System.out.println("push: 4");
53         stack.push(9);
54         System.out.println("push: 9");
55         stack.push(7);
56         System.out.println("push: 7");
57         System.out.println("Push result: " + stack.getStackElement().toString());
58         stack.pop();
59 
60     }
61 }

结果:

==== Push ==== 
push: 4
push: 9
push: 7
Push result: [4, 9, 7]
pop: 7
pop: 9
pop: 4

==== Push Aagin ==== 
push: 4
push: 9
push: 7
Push result: [4, 9, 7]
pop: 4
pop: 9
pop: 7

posted on 2019-09-08 19:47  自律的蚂蚁  阅读(195)  评论(0)    收藏  举报

导航