如何用两个栈模拟一个队列

这是当年《数据结构》课的一个问题,拿出来巩固一下。使用两个栈,其中一个栈stack1负责添加元素,另外一个栈stack2负责弹出元素。分两种情况,如果stack2不空则直接弹出,否则逐个弹出stack1中的元素放入stack2中,然后再从stack2中弹出一个元素。

package Algorithm.learn;

/**
 * Created by liujinhong on 2017/3/7.
 * 用两个栈来模拟对类
 */
public class StackQueue<E> {
    //stack1负责加入元素
    ListStack<E> stack1 = new ListStack<E>();
    //stack2负责弹出元素
    ListStack<E> stack2 = new ListStack<E>();

    public boolean isEmpty() {
        return stack1.isEmpty() && stack2.isEmpty();
    }

    public void offer(E e) {
        stack1.push(e);
    }

    public E poll() {
        if (stack2.isEmpty()) {
            while (! stack1.isEmpty()) {
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }

    public static void main(String[] args) {
        StackQueue<Integer> stackQueue = new StackQueue<>();
        for (int i = 0; i < 20; i++) {
            stackQueue.offer(i);
        }

        for (int i = 0; i < 20; i++) {
            System.out.println(stackQueue.poll());
        }
    }
}
原文地址:https://www.cnblogs.com/liujinhong/p/6513440.html