栈和队列:两个栈组成队列

要求:编写一个算法,用两个栈实现队列,支持队列的基本操作(add, peek, pop)。

思路:栈的特点是先进后出,而队列的特点是先进先出。

所以为实现队列元素的进出方法,我们可以用两个栈正好把顺序颠倒过来。

具体实现是将一个栈作为压入栈,所以往队列里添加的数据都压入这个栈,记为 in;

另一个栈弹出栈,所有对队列元素进行获取的操作都在这个栈进行,记为 out;

 操作如图所示

需要注意的两点:

1. 每次将 in 中的数据压入 out 时,必须把 in 中所有数据一次性压入。

2. 如果 out 中不为空,则决不能往其中压入数据。

 违反上述两点都会产生错误。

import java.util.*;

public class TwoStacksQueue
{
    Stack<Integer> in;
    Stack<Integer> out;

    public TwoStacksQueue()
    {
        in = new Stack<Integer>();
        out = new Stack<Integer>();
    }

    public void add(int x)
    {
        in.push(x);
    }

    public int peek()
    {
        if(in.isEmpty() && out.isEmpty())
        {
            throw new RuntimeException("Queue is Empty!");
        }
        else if(out.isEmpty())
        {
            while(!in.isEmpty())
            {
                out.push(in.pop());
            }
        }

        return out.peek();
    }

    public int pop()
    {
        if(in.isEmpty() && out.isEmpty())
        {
            throw new RuntimeException("Queue is Empty!");
        }
        else if(out.isEmpty())
        {
            while(!in.isEmpty())
            {
                out.push(in.pop());
            }
        }

        return out.pop();
    }
}

 参考资料:程序员代码面试指南IT名企算法与数据结构题目最优解, 左程云

原文地址:https://www.cnblogs.com/2015110615L/p/6658600.html