首页 > 其他 > 详细

LintCode Implement Queue by Two Stacks

时间:2016-08-21 15:06:55      阅读:121      评论:0      收藏:0      [点我收藏+]

1. stack(先进后出):

pop 拿出并返回最后值; peek 返回最后值; push 加入新值在后面并返回此值。

2. queue(先进先出) :

poll = remove 拿出并返第一个值; element = peek 返第一个值; add = offer 加入新值在后面并返回true/false。

做此题时, 第一个stack为基础, 第二个stack为媒介来颠倒顺序, 加时从第一个加, 取时从第二个取。

public class Queue {
    private Stack<Integer> stack1;
    private Stack<Integer> stack2;

    public Queue() {
       stack1 = new Stack<Integer>();
       stack2 = new Stack<Integer>();
       // do initialization if necessary
    }
    
    public void push(int element) {
        stack1.push(element);
        // write your code here
    }

    public int pop() {
        if(!stack2.empty()){
            return stack2.pop();
        } else{
            while(stack1.size() > 0){
                stack2.push(stack1.pop());
            }
            if(!stack2.empty()){
                return stack2.pop();
            } else return -1;
        }
        // write your code here
    }

    public int top() {
        if(!stack2.empty()){
            return stack2.peek();
        } else{
            while(stack1.size() > 0){
                stack2.push(stack1.pop());
            }
            if(!stack2.empty()){
                return stack2.peek();
            } else return -1;
        }
        // write your code here
    }
}

 

LintCode Implement Queue by Two Stacks

原文:http://www.cnblogs.com/LittleAlex/p/5792646.html

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