generic queue using linkedlist collection class

PHOTO EMBED

Wed May 29 2024 19:25:20 GMT+0000 (Coordinated Universal Time)

Saved by @exam123

import java.util.LinkedList;
 
class GenericQueue<T> {
    private LinkedList<T> queue;
 
    public GenericQueue() {
        queue = new LinkedList<>();
    }
 
    // Method to add an element to the queue
    public void enqueue(T element) {
        queue.addLast(element);
    }
 
    // Method to remove and return the element at the front of the queue
    public T dequeue() {
        if (isEmpty()) {
            throw new IllegalStateException("Queue is empty");
        }
        return queue.removeFirst();
    }
 
    // Method to check if the queue is empty
    public boolean isEmpty() {
        return queue.isEmpty();
    }
 
    // Method to get the size of the queue
    public int size() {
        return queue.size();
    }
}
 
public class Main {
    public static void main(String[] args) {
        GenericQueue<String> stringQueue = new GenericQueue<>();
 
        // Enqueue some elements
        stringQueue.enqueue("First");
        stringQueue.enqueue("Second");
        stringQueue.enqueue("Third");
 
        // Dequeue and print elements
        System.out.println("Dequeueing elements:");
        while (!stringQueue.isEmpty()) {
            System.out.println(stringQueue.dequeue());
        }
    }
}
 
content_copyCOPY