码迷,mamicode.com
首页 > 其他好文 > 详细

Implement Queue by Two Stacks

时间:2016-07-19 09:34:08      阅读:99      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!