剑指offer_用两个栈来实现一个队列

题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
解题思路
stack1 栈用来处理入栈(push)操作,stack2 栈用来处理出栈(pop)操作。一个元素进入 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() throws Exception {
12         if(stack2.isEmpty())
13         while(!stack1.isEmpty())
14         stack2.push(stack1.pop());
15         if (out.isEmpty())
16             throw new Exception("queue is empty");
17         return stack2.pop();
18     }
19 }

pop的时候如果stack2是空才加载stack1的内容,然后弹出去

posted @ 2019-08-11 16:00  chyblogs  阅读(128)  评论(0)    收藏  举报