首页 > 其他 > 详细

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

时间:2018-09-23 23:22:53      阅读:173      评论:0      收藏:0      [点我收藏+]

题目:

  用两个栈来实现一个队列,完成队列的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 }

 

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

原文:https://www.cnblogs.com/rgever/p/9693761.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!