两个栈实现队列(D)

发布于:2025-02-10 ⋅ 阅读:(34) ⋅ 点赞:(0)
import java.util.Stack;

public class TwoStackQueue {
    private Stack<Integer> stackPush;
    private Stack<Integer> stackPop;

    public TwoStackQueue() {
        stackPush = new Stack<Integer>();
        stackPop = new Stack<Integer>();
    }

    private void pushToPop() {
        if (stackPop.empty()) {
            while (!stackPush.empty()) {
                stackPop.push(stackPush.pop());
            }
        }
    }

    public void add(int pushInt) {
        stackPush.push(pushInt);
        pushToPop();
    }

    public int poll() {
        if (stackPop.empty() && stackPush.empty()) {
            throw new RuntimeException("Queue is empty!");
        }
        pushToPop();
        return stackPop.pop();
    }

    public int peek() {
        if (stackPop.empty() && stackPush.empty()) {
            throw new RuntimeException("Queue is empty!");
        }
        pushToPop();
        return stackPop.peek();
    }

    public static void main(String[] args) {
        TwoStackQueue queue = new TwoStackQueue();
        queue.add(1);
        queue.add(2);
        queue.add(3);
        System.out.println(queue.poll());
        System.out.println(queue.peek());
        System.out.println(queue.poll());

    }
}

这个算法通过两个栈结构巧妙地模拟了一个队列的行为,其中stackPush用于处理入队操作,而stackPop用于处理出队操作。当需要出队时,算法会检查stackPop是否为空,如果为空,则将stackPush中的所有元素逆序转移到stackPop中,从而确保stackPop的栈顶元素是队列的头部元素。这种方法使得入队操作的时间复杂度为O(1),而出队操作在最坏情况下的时间复杂度为O(n),但平均时间复杂度仍为O(1),因为每个元素只被移动一次。整体上,该算法高效地利用了栈的后入先出特性来实现了队列的先进先出特性。


网站公告

今日签到

点亮在社区的每一天
去签到