Problem Statement: Write a Java program to implement a basic queue using LinkedList to enqueue and dequeue elements.
Here’s a basic implementation of a queue using a LinkedList
in Java to enqueue and dequeue elements.
package com.javacodepoint.collection;
import java.util.LinkedList;
public class BasicQueue<T> {
private LinkedList<T> queue;
public BasicQueue() {
queue = new LinkedList<>();
}
// Method to enqueue (add) an element to the end of the queue
public void enqueue(T data) {
queue.addLast(data);
}
// Method to dequeue (remove) and return the element from 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 static void main(String[] args) {
BasicQueue<Integer> myQueue = new BasicQueue<>();
// Enqueue elements
myQueue.enqueue(1);
myQueue.enqueue(2);
myQueue.enqueue(3);
System.out.println("Queue Size: " + myQueue.size());
// Dequeue elements
System.out.println("Dequeued Element: " + myQueue.dequeue());
System.out.println("Dequeued Element: " + myQueue.dequeue());
System.out.println("Queue Size after Dequeue: " + myQueue.size());
}
}
OUTPUT:
Queue Size: 3
Dequeued Element: 1
Dequeued Element: 2
Queue Size after Dequeue: 1
Explanation:
BasicQueue
Class: This class represents a basic queue implemented using aLinkedList
. It uses generics to make it suitable for storing elements of any data type.- Constructor: In the constructor, we initialize a
LinkedList
namedqueue
to hold the elements of the queue. enqueue(T data)
: This method adds an element to the end of the queue using theaddLast()
method of theLinkedList
.dequeue()
: This method removes and returns the element from the front of the queue using theremoveFirst()
method of theLinkedList
. If the queue is empty, it throws anIllegalStateException
.isEmpty()
: This method checks if the queue is empty by using theisEmpty()
method of theLinkedList
.size()
: This method returns the size of the queue by using thesize()
method of theLinkedList
.main
method: In themain
method, we create an instance of theBasicQueue
class, enqueue elements, and dequeue elements, and print the size of the queue before and after dequeue operations.
This basic queue implementation provides the fundamental functionality of a queue, allowing you to enqueue and dequeue elements while maintaining their order.
See also: Create a Custom LinkedList in Java