首页 > 试题广场 >

用两个栈实现一个队列的功能?要求给出算法和思路!

[问答题]
用两个栈实现一个队列的功能?要求给出算法和思路!

主要实现方式如下,其中stack1是输入栈用来进行对列的输入,输出栈是stack2 用来做队列的输出,这道题目通过画图将会更加直观的展现,因为栈的特点是先进后出,而对列的特点是先进先出,通过两次入栈,可以达到先进的也可以先出,这样就实现了栈来模拟对列的操作。

public class StackBuildQueue {

Stack<Integer> stack1 = new Stack<Integer>(); //输入栈

Stack<Integer> stack2 = new Stack<Integer>(); //输出栈

//直接将将数据存放到输入栈中
public void push(int node) {
    stack1.push(node);
}

public int pop() throws Exception{
    //当输出栈为空则将输入栈的数据存储到输出栈中
    if (stack2.size() == 0) {
        while (!stack1.empty()) {
            stack2.push(stack1.pop());
        }
    }
    //如果输出栈不为空则将输出栈的的数据直接输出
    if (!stack2.empty()) {
        return  stack2.pop();
    }else
    {
        throw  new Exception("stack is empty cant pop");
    }

}

}

发表于 2017-01-23 11:53:38 回复(0)