Java Program to Implement the Queue Data Structure

Java Program to Implement the queue data structure

Java Queue Interface

  • The Java Queue interface is a part of the Java Collections Framework and provides an ordered collection of elements that follow the FIFO (First-In-First-Out) principle.
  • It extends the Collection interface and adds methods for inserting, removing, and examining the elements in the queue.
    • You must be familiar with following topics to understand the correspond example Such as: Java Queue Interface and Java Generics.
  • To understand the Java Program to Implement the Queue Data Structure, Read the Complete Article.

Steps to Implement the Queue Data Structure.

  • Here are the steps to Implement the Queue Data Structure.
    • Decide on the implementation method, whether to use the built-in LinkedList class or create a custom Queue class.
    • If using the built-in LinkedList class, import it using import java.util.LinkedList;.
    • Create a LinkedList instance to represent the queue.
    • Add elements to the queue using the add() or offer() method.
    • Remove elements from the queue using the remove() or poll() method.
    • Retrieve the first element of the queue without removing it using the peek() method.
    • Optionally, implement additional methods to get the size of the queue or check if it is empty.
    • If creating a custom Queue class, define the methods for enqueueing, dequeueing, peeking, and other desired functionality.
    • Test the implementation to ensure that it works correctly.

Generics provide several benefits which Includes:

Improved type safety: Generics provide compile-time type checking, which helps to prevent type errors at runtime.
Reusability: Generics allow you to write code that can be used with different data types, reducing the need to write duplicate code.
Code clarity: Generics make the code more readable and easier to understand, as the type of data being used is explicitly specified.

Implementation Of Queue Data Structure in java .

Let’s look at the Java Program to Implement the Queue Data Structure to perform certain operations.

Example 1: Java Program to implement Stack

Run
public class Main {

    private Object[] arr;
    private int top;
    private int capacity;

    public Main(int size) {
        arr = new Object[size];
        capacity = size;
        top = -1;
    }

    public void push(T item) {
        if (isFull()) {
            throw new IllegalStateException("Stack is full");
        }
        arr[++top] = item;
    }

    public T pop() {
        if (isEmpty()) {
            throw new IllegalStateException("Stack is empty");
        }
        T item = (T) arr[top];
        arr[top--] = null;
        return item;
    }

    public T peek() {
        if (isEmpty()) {
            throw new IllegalStateException("Stack is empty");
        }
        return (T) arr[top];
    }

    public boolean isEmpty() {
        return top == -1;
    }

    public boolean isFull() {
        return top == capacity - 1;
    }

    public int size() {
        return top + 1;
    }

    public static void main(String[] args) {
        Main stack = new Main(4);
        stack.push(15);
        stack.push(25);
        stack.push(50);
        System.out.println("Size of stack: " + stack.size());
        System.out.println("Top element: " + stack.peek());
        System.out.println("Popped element: " + stack.pop());
        System.out.println("Size of stack: " + stack.size());
        System.out.println("Top element: " + stack.peek());
    }
}

Output

Size of stack: 3
Top element: 50
Popped element: 50
Size of stack: 2
Top element: 25

Example 2 :Java Program to Implement Stack

Run
import java.util.*;

public class Main
{

  public static boolean isBalanced (String str)
  {
    Stack < Character > stack = new Stack <> ();
    for (int i = 0; i < str.length (); i++)
      {
	char ch = str.charAt (i);
	if (ch == '(' || ch == '{' || ch == '[')
	  {
	    stack.push (ch);
	  }
	else if (ch == ')' || ch == '}' || ch == ']')
	  {
	    if (stack.isEmpty ())
	      {
		return false;
	      }
	    char top = stack.pop ();
	    if ((ch == ')' && top != '(') || (ch == '}' && top != '{')
		|| (ch == ']' && top != '['))
	      {
		return false;
	      }
	  }
      }
    return stack.isEmpty ();
  }

  public static void main (String[]args)
  {
    String str1 = "([])(){}";
    String str2 = "([)]";
    System.out.println (str1 + " is balanced: " + isBalanced (str1));
    System.out.println (str2 + " is balanced: " + isBalanced (str2));
  }
}

Output

([])(){} is balanced: true
([)] is balanced: false

Example 3: Java Program to Implement stack using Queue interface.

Run
import java.util.LinkedList;
import java.util.Queue;

public class Main {

    private Queue q1 = new LinkedList();
    private Queue q2 = new LinkedList();
    private int size = 0;

    public void push(T item) {
        q1.add(item);
        size++;
    }

    public T pop() {
        if (size == 0) {
            throw new IllegalStateException("Stack is empty");
        }
        while (q1.size() > 1) {
            q2.add(q1.remove());
        }
        T item = q1.remove();
        size--;
        Queue temp = q1;
        q1 = q2;
        q2 = temp;
        return item;
    }

    public T peek() {
        if (size == 0) {
            throw new IllegalStateException("Stack is empty");
        }
        while (q1.size() > 1) {
            q2.add(q1.remove());
        }
        T item = q1.remove();
        q2.add(item);
        Queue temp = q1;
        q1 = q2;
        q2 = temp;
        return item;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public int size() {
        return size;
    }

    public static void main(String[] args) {
        Main stack = new Main();
        stack.push(10);
        stack.push(20);
        stack.push(30);
        System.out.println("Size of stack: " + stack.size());
        System.out.println("Top element: " + stack.peek());
        System.out.println("Popped element: " + stack.pop());
        System.out.println("Size of stack: " + stack.size());
        System.out.println("Top element: " + stack.peek());
    }
}

Output

Size of stack: 3
Top element: 30
Popped element: 30
Size of stack: 2
Top element: 20

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription