首页 > 其他 > 详细

用栈实现队列

时间:2017-10-11 15:09:24      阅读:257      评论:0      收藏:0      [点我收藏+]

正如标题所述,你需要使用两个栈来实现队列的一些操作。

队列应支持push(element),pop() 和 top(),其中pop是弹出队列中的第一个(最前面的)元素。

pop和top方法都应该返回第一个元素的值。

比如push(1), pop(), push(2), push(3), top(), pop(),你应该返回1,2和2

 

思路:

1、push元素时,直接进栈stack1

2、pop或top时,判断stack2是否为空,若为空,将stack1中的元素逆序插入stack2。然后返回stack2.pop()  或 stack2.peek()。

 

知识点:

栈是Vector的一个子类,它实现了一个标准的后进先出的栈。堆栈只定义了默认构造函数Stack(),用来创建一个空栈。 堆栈除了包括由Vector定义的所有方法,也定义了自己的一些方法。

1、empty():测试堆栈是否为空

2、push(element):将项压入堆栈顶部

3、top():移除堆栈顶部的对象,并作为此函数的值返回该对象

4、peek():查看堆栈顶部的对象,但不从堆栈中移除

5、search():返回对象在堆栈中的位置,以1为基数。

 

 

代码:

public class MyQueue {
    private Stack<Integer> stack1;
    private Stack<Integer> stack2;
    public MyQueue() {
        // do intialization if necessary
        stack1 = new Stack<Integer>();
        stack2 = new Stack<Integer>();
    }

    /*
     * @param element: An integer
     * @return: nothing
     */
    public void push(int element) {
        // write your code here
        stack1.push(element);
    }
    /*
     * @return: An integer
     */
    public int pop() {
        // write your code here
        if(stack2.empty()){
            while(!stack1.empty()){
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }

    /*
     * @return: An integer
     */
    public int top() {
        // write your code here
        if(stack2.empty()){
            while(!stack1.empty()){
                stack2.push(stack1.pop());
            }
        }
        return stack2.peek();
    }
}

用栈实现队列

原文:http://www.cnblogs.com/yanernanfei/p/7650313.html

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