剑指Offer第五题:用两个栈实现队列

问题描述

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

问题分析

我们都知道栈是先进后出,队列是先进先出。我们如果先让数字进入栈1,进入完成后,再出站进入栈2,待栈二完成后再统一出栈,那么就可以实现了(不会画图,真丑)

算法分析

  • 将stack1作为进栈存储数字,待合适的时机再出栈到stack2。
  • 进队列的操作:首先进入stack1,然后判断stack2是否为空,如果stack2为空,那么直接将stack1里面的输有数据出栈,全部进入Stack2中。如果stack2,不为空,那么我们不做任何操作,因为Stack2有数据,在从stack1弄到stack2中那么就违反了先进先出的规则。
  • 出队列操作,如果stack2不为空,那么直接进行出队列操作,如果Stack2为空,那么我们需要将stack1的数据转移到stack2中再进行出栈操作。

源代码

 1 public class Solution {
 2         Stack<Integer> stack1 = new Stack<Integer>();
 3         Stack<Integer> stack2 = new Stack<Integer>();
 4         
 5         public void push(int node) {
 6             stack1.push(node);
 7             if(stack2.isEmpty()) {
 8                 while(!stack1.isEmpty()) {
 9                     int op=stack1.pop();
10                     stack2.push(op);
11                 }
12             }
13         }
14         
15         public int pop() {
16             if(stack2.isEmpty()) {
17                 while(!stack1.isEmpty()) {
18                     int op =stack1.pop();
19                     stack2.push(op);
20                 }
21                 
22                 return stack2.pop();
23             }else {
24                 return stack2.pop();
25             }
26         
27         }
28     }

 

 

ps:如有不足请多指教

 

posted @ 2018-09-02 17:38  轻抚丶两袖风尘  阅读(120)  评论(0)    收藏  举报