005 两个栈组成队列

一:主题

1.题目

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

2.程序思路

  从队列与栈的特点上进行写程序。

  首先,栈的特点是先进后出,而队列是先进先出。

  所以,要实现队列,需要使用两个栈进行组合。

  做法,我以为,让第一个作为push的栈,然后,pop的时候,将第一个栈中的数据都转移到栈2,然后把最上面的弹出来。

  注意点:可能一次性push多个数据,所以,在pop的时候,再去清空栈1。  

3.程序

 1 package first;
 2 
 3 import com.sun.org.apache.bcel.internal.generic.PUSH;
 4 import sun.awt.windows.ThemeReader;
 5 
 6 import javax.xml.soap.Node;
 7 import java.util.Stack;
 8 
 9 public class StackWithTwoQueues {
10     //作为入栈
11     private static Stack<Integer> stack1=new Stack<Integer>();
12     //作为出栈
13     private static Stack<Integer> stack2=new Stack<Integer>();
14 
15     /**
16      * 测试
17      * @param args
18      */
19     public static void main(String[] args) {
20         push(1);
21         push(2);
22         push(5);
23         int val=pop();
24         System.out.println(val);
25         push(1);
26         int val2=pop();
27         System.out.println(val2);
28 
29     }
30     /**
31      * 实现push方法
32      */
33 
34     public static void push(int val){
35         stack1.push(val);
36     }
37 
38     /**
39      * 实现pop方法
40      * @return
41      */
42     public static int pop(){
43         //将数据都放到2中
44         while (!stack1.isEmpty()){
45             stack2.push(stack1.pop());
46         }
47         if(!stack2.isEmpty()){
48             int node=stack2.pop();
49             return node;
50         }else {
51             throw new RuntimeException("null");
52         }
53     }
54 }

4.现象

  

猜你喜欢

转载自www.cnblogs.com/juncaoit/p/10244885.html
005