剑指offer(五):用两个栈实现一个队列

题目:

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

解决办法:

  队列先进先出,栈先进后出(stack1和stack2)

  其实主要要注意的点是:

    ①在添加时直接往第一个添加即可

    ②在删除时分情况,

    第一:如果stack2不为空,则直接弹出stack2中的元素即可,因为stack2中的肯定要比stack1中的元素加进来早

    第二:如果stack2是空的,则把stack1中的元素一一弹出并加入到stack2中,之后再弹出

如图测试数据:(结合下面代码看)

 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(stack2.isEmpty()){
13             while(!stack1.isEmpty()){
14                 stack2.push(stack1.pop());
15             }
16             return stack2.pop();
17         }else{
18             return stack2.pop();
19         }
20     }
21     
22     public static void main(String[] args) {
23         Solution s = new Solution();
24         //
25         s.push(1);
26         //
27         s.push(2);
28         //
29         s.push(3);
30         //
31         int a = s.pop();
32         System.out.println(a);
33         //
34         int b = s.pop();
35         System.out.println(b);
36         //
37         s.push(4);
38         //
39         int c = s.pop();
40         System.out.println(c);
41         //
42         s.push(5);
43         //
44         int d = s.pop();
45         System.out.println(d);
46         //
47         int e = s.pop();
48         System.out.println(e);
49     }
50 }

猜你喜欢

转载自www.cnblogs.com/rgever/p/9693761.html