首页 > 其他 > 详细

Implement Queue by Two Stacks

时间:2016-07-19 09:34:05      阅读:290      评论:0      收藏:0      [点我收藏+]

As the title described, you should only use two stacks to implement a queue‘s actions.

The queue should support push(element)pop() and top() where pop is pop the first(a.k.a front) element in the queue.

Both pop and top methods should return the value of first element.

Example
push(1)
pop()     // return 1
push(2)
push(3)
top()     // return 2
pop()     // return 2

 1 public class Queue {
 2     private Stack<Integer> stack1;
 3     private Stack<Integer> stack2;
 4 
 5     public Queue() {
 6         // do initialization if necessary
 7         stack1 = new Stack<Integer>();
 8         stack2 = new Stack<Integer>();
 9     }
10 
11     public void push(int element) {
12         stack1.push(element);
13     }
14 
15     public int pop() {
16         if (stack2.size() != 0) {
17             return stack2.pop();
18         }
19 
20         while (stack1.size() != 0) {
21             stack2.push(stack1.pop());
22         }
23 
24         if (stack2.size() != 0) {
25             return stack2.pop();
26         }
27         return -1;
28     }
29 
30     public int top() {
31 
32         if (stack2.size() != 0) {
33             return stack2.peek();
34         }
35         while (stack1.size() != 0) {
36             stack2.push(stack1.pop());
37         }
38 
39         if (stack2.size() != 0) {
40             return stack2.peek();
41         }
42         return -1;
43     }
44 }

 

 

Implement Queue by Two Stacks

原文:http://www.cnblogs.com/beiyeqingteng/p/5683314.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!