首页 > 其他 > 详细

[lintcode medium]Implement Queue by Two Stacks

时间:2016-01-06 06:46:38      阅读:188      评论:0      收藏:0      [点我收藏+]

Implement Queue by Two Stacks

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
Challenge

implement it by two stacks, do not use any other data structure and push, pop and top should be O(1) by AVERAGE.

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

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

    public int pop() {
        // write your code here
        if(stack2.isEmpty())
        {
            while(!stack1.isEmpty())
            {
                stack2.push(stack1.pop());
            }
        }
        
        return stack2.pop();
    }

    public int top() {
        // write your code here
        if(stack2.isEmpty())
        {
            while(!stack1.isEmpty())
            {
                stack2.push(stack1.pop());
            }
        }
        
        return stack2.peek();
    }
}

 

 

[lintcode medium]Implement Queue by Two Stacks

原文:http://www.cnblogs.com/kittyamin/p/5104264.html

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