溫馨提示×

如何在Java中使用LinkedList實現(xiàn)隊列操作

小樊
84
2024-08-16 23:45:47
欄目: 編程語言

在Java中,可以使用LinkedList來實現(xiàn)隊列的操作。下面是一個簡單的示例代碼:

import java.util.LinkedList;

public class QueueExample {
    private LinkedList<Integer> queue = new LinkedList<>();

    public void enqueue(int value) {
        queue.addLast(value);
    }

    public int dequeue() {
        if (queue.isEmpty()) {
            throw new IllegalStateException("Queue is empty");
        }
        return queue.removeFirst();
    }

    public int peek() {
        if (queue.isEmpty()) {
            throw new IllegalStateException("Queue is empty");
        }
        return queue.getFirst();
    }

    public boolean isEmpty() {
        return queue.isEmpty();
    }

    public int size() {
        return queue.size();
    }

    public static void main(String[] args) {
        QueueExample queue = new QueueExample();

        queue.enqueue(1);
        queue.enqueue(2);
        queue.enqueue(3);

        System.out.println("Dequeue: " + queue.dequeue());
        System.out.println("Peek: " + queue.peek());
        System.out.println("Is empty: " + queue.isEmpty());
        System.out.println("Size: " + queue.size());
    }
}

在上面的代碼中,我們使用LinkedList來實現(xiàn)隊列的操作,包括enqueue入隊、dequeue出隊、peek獲取隊首元素、isEmpty判斷隊列是否為空以及size獲取隊列的大小等操作。通過調(diào)用enqueue、dequeue、peek、isEmpty和size等方法,可以實現(xiàn)隊列的基本操作。

0