用两个栈来实现一个队列

题目:

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

限制:

时间限制:1秒 空间限制:32768K 热度指数:240468

 1 package com.algorithm;
 2 
 3 import java.util.Stack;
 4 
 5 /**
 6  * 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型
 7  * @日期:2018年6月24日 下午9:17:49
 8  * @作者:Chendb
 9  */
10 public class Queue {
11 
12     Stack<Integer> stack1 = new Stack<Integer>();
13     Stack<Integer> stack2 = new Stack<Integer>();
14     
15     public static void main(String[] args) {
16         Queue queue = new Queue();
17         //System.out.println(queue.pop());
18         queue.push(1);
19         queue.push(3);
20         
21         System.out.println(queue.pop());
22         queue.push(2);
23         
24         System.out.println(queue.pop());
25         System.out.println(queue.pop());
26     }
27     
28     public void push(int node) {
29         stack1.push(node);
30     }
31     
32     public int pop() {
33         stack2.clear();
34         
35         while (!stack1.isEmpty()) {
36             stack2.push(stack1.pop());
37         }
38         
39         if (stack2.isEmpty()) {
40             return 0;
41         }
42         
43         int result = stack2.pop();
44         
45         while (!stack2.isEmpty()) {
46             stack1.push(stack2.pop());
47         }
48         
49         return result;
50     }
51     
52 }
View Code

 

posted @ 2018-06-24 22:17  无聊的小剑  阅读(232)  评论(0编辑  收藏  举报