by BehindJava

What is a Queue in Data Structures

Home » datastructures » What is a Queue in Data Structures

In this blog, we are going to learn about Queue and its implementation with a detailed example.

Queue

  • A Queue is a linear list of elements in which deletions can take place only at one end, called the ‘FRONT’ and insertions can take place only at the other end, called the ‘REAR’.
  • Queues are also called as FIFO list. queue
  • A Queue is an Abstract Data Type.
  • add - also called as enqueue and adds an item to the end of the queue.
  • remove - also called as dequeue and removes the item at the front of the queue.
  • peeK - get the item at the front of the queue, but don’t remove it.

Dequeue

  • Dequeue (aka Double-ended queue) is a linear list in which elements can be added or removed at either end but not in the middle.
  • Dequeues are represented using circular array. Thus Dequeue[1] comes after Dequeue[N]
  • Two types of Dequeue are:
  • Input-restricted Dequeue: allows insertion only at one end while deletion in both ends of the list.
  • Output-restricted Dequeue: allows deletion only at one end while insertion at both the ends of the list.

Priority Queue

  • A Priority Queue is a collection of elements such that each element has been assigned a priority and such that the order in which elements are processed comes from the following rules:
  • An element of higher priority is processed before any element of lower priority.
  • Two elements with the same priority are processed according to the order in which they were added to the queue.
  • Example: Time sharing systems: Programs of high priority are processed first.
import java.util.Iterator;
import java.util.PriorityQueue;

public class BehindJava {

	public static void main(String[] args) {

		PriorityQueue<String> queue = new PriorityQueue<String>();
		queue.add("aa");
		queue.add("bb");
		queue.add("cc");
		queue.add("dd");
		queue.add("ee");

		System.out.println(queue);
		System.out.println("head:" + queue.element());
		System.out.println("head:" + queue.peek());
		Iterator itr = queue.iterator();
		System.out.println("iterating the queue elements:");
		while (itr.hasNext()) {
			System.out.print(" " + itr.next());
		}
		queue.remove();
		queue.poll();
		System.out.println();
		Iterator<String> itr2 = queue.iterator();
		System.out.println("after removing two elements:");
		while (itr2.hasNext()) {
			System.out.print(" " + itr2.next());
		}
	}
}

Output:

[aa, bb, cc, dd, ee]
head:aa
head:aa
iterating the queue elements:
 aa bb cc dd ee
after removing two elements:
 cc dd ee