Queue Implementation using LinkedList

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:

  1. BasicQueue Class: This class represents a basic queue implemented using a LinkedList. It uses generics to make it suitable for storing elements of any data type.
  2. Constructor: In the constructor, we initialize a LinkedList named queue to hold the elements of the queue.
  3. enqueue(T data): This method adds an element to the end of the queue using the addLast() method of the LinkedList.
  4. dequeue(): This method removes and returns the element from the front of the queue using the removeFirst() method of the LinkedList. If the queue is empty, it throws an IllegalStateException.
  5. isEmpty(): This method checks if the queue is empty by using the isEmpty() method of the LinkedList.
  6. size(): This method returns the size of the queue by using the size() method of the LinkedList.
  7. main method: In the main method, we create an instance of the BasicQueue 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

Java logical programs list


Java Basic Programs

Java Programs based on the Collection Framework

Leave a Reply

Your email address will not be published. Required fields are marked *