Fork me on GitHub

用两个栈实现队列

题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
 1 import java.util.Stack;
 2 
 3 //用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
 4 
 5 public class Main05 {
 6     public static void main(String[] args) {
 7         
 8     }
 9     
10     public class Solution {
11         Stack<Integer> stack1 = new Stack<Integer>();
12         Stack<Integer> stack2 = new Stack<Integer>();
13         
14         public void push(int node) {
15             stack1.push(node);
16         }
17         
18         public int pop() {
19             Integer re = null;
20             if(!stack2.isEmpty()) {
21                 re = stack2.pop();
22             }else {
23                 while(!stack1.isEmpty()) {
24                     re = stack1.pop();
25                     stack2.push(re);
26                 }
27                 if(!stack2.isEmpty()) {
28                     re = stack2.pop();
29                 }
30                 
31             }
32             return re;
33         }
34     }

 

posted @ 2019-06-10 20:34  gentleKay  阅读(622)  评论(0编辑  收藏  举报