首页 > 其他 > 详细

Implement Queue by Two Stacks

时间:2017-02-14 12:24:47      阅读:272      评论: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.


分析

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




Implement Queue by Two Stacks

原文:http://www.cnblogs.com/zhxshseu/p/9415037aea8647d4817529ba5f792bde.html

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