温馨提示×

怎么用Java栈实现队列

小亿
86
2023-11-09 00:47:30
栏目: 编程语言

使用Java的栈来实现队列可以通过两个栈来实现。一个栈用来存储队列的元素,另一个栈用来辅助操作。

具体实现步骤如下:

  1. 创建两个栈,一个用于存储队列的元素,命名为stack1,另一个用于辅助操作,命名为stack2
  2. 实现队列的入队操作enqueue,即将元素添加到stack1中。
  3. 实现队列的出队操作dequeue,首先判断stack2是否为空,若为空,则将stack1中的元素依次弹出并压入stack2中,然后从stack2中弹出栈顶元素作为出队元素;若stack2不为空,则直接从stack2中弹出栈顶元素作为出队元素。
  4. 实现队列的获取队首元素操作peek,同样需要先判断stack2是否为空,若为空,则将stack1中的元素依次弹出并压入stack2中,然后获取stack2的栈顶元素作为队首元素;若stack2不为空,则直接获取stack2的栈顶元素作为队首元素。
  5. 实现队列的判空操作isEmpty,判断stack1stack2是否都为空,若是,则队列为空;否则,队列不为空。

下面是Java代码的实现:

import java.util.Stack;

public class QueueWithStacks {
    private Stack<Integer> stack1;
    private Stack<Integer> stack2;

    public QueueWithStacks() {
        stack1 = new Stack<>();
        stack2 = new Stack<>();
    }

    public void enqueue(int element) {
        stack1.push(element);
    }

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

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

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

使用示例:

public class Main {
    public static void main(String[] args) {
        QueueWithStacks queue = new QueueWithStacks();
        queue.enqueue(1);
        queue.enqueue(2);
        queue.enqueue(3);
        System.out.println(queue.dequeue());  // 输出: 1
        System.out.println(queue.peek());  // 输出: 2
        System.out.println(queue.isEmpty());  // 输出: false
    }
}

以上就是使用Java的栈实现队列的方法。

0