05 用两个栈实现队列

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

 

 1 import java.util.Stack;
 2 import java.util.*;
 3 //这道题果然是用 push和pop函数来当做队列的入队和出队
 4 public class Solution {
 5     //栈A用来作入队列
 6     //栈B用来出队列,当栈B为空时,栈A全部出栈到栈B,栈B再出栈(即出队列)
 7     Stack<Integer> stack1 = new Stack<Integer>();
 8     Stack<Integer> stack2 = new Stack<Integer>();
 9     
10     public void push(int node) {
11         stack1.push(node);
12     }
13     
14     public int pop() {
15         if(!stack2.empty()){
16             return stack2.pop();
17         }else{
18             while( !stack1.empty()){
19                 stack2.push(stack1.pop());
20             }
21             return stack2.pop();
22         }
23     }
24 }

 

posted @ 2019-06-27 10:30  淡如水94  阅读(108)  评论(0)    收藏  举报