Queue

Queue
public class QueueImpl<T> implements Queue<T> {

private Node<T> head = null;
private Node<T> tail = null;
private int size = 0;

private static class Node<T> {

private T data;
private Node<T> next;

public Node(T data) {
this.data = data;
}

}

@Override
public void enqueue(T val) {
Node<T> newNode = new Node<T>(val);
size++;
if (head == null) {
head = tail = newNode;
return;
}
tail.next = newNode;
tail = newNode;
}

@Override
public T dequeue() {
if (head == null)
throw new RuntimeException("Queue is Empty");
T data = head.data;
size--;
head = head.next;
if (head == null)
tail = null;
return data;
}

@Override
public T peek() {
if (head == null)
throw new RuntimeException("Queue is Empty");
return head.data;
}

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

@Override
public int size() {
return size;
}

}
Queue<Integer> queue = new LinkedList<>();
Queue<Integer> queue = new PriorityQueue<>();
  1. Web Server Request management where you want to server first come first serve basis.
  2. Used to do Breadth-First Search(BFS) on a graph.
The below table represents the worst-case time complexity
+-----------+-------+
| Operation | Queue |
+-----------+-------+
| enqueue | O(1) |
| dequeue | O(1) |
| peek | O(1) |
| search | O(n) |
| size | O(1) |
+-----------+-------+

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Using Pytest

How Change Data Capture is used for Real-Time Data Integration and Analytics

Fundamentals of engineering documentation

Agoric. The beginning.

Sorting Algorithms in Python

#day49. One algorithm to rule them all #50storychallenge #100daychallenge

Product Video — Hoyam Large Storage Basket.compressed

Image

Making OpenVPN work with Squid Proxy in AWS EC2 / VPS

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Roughnoteone

Roughnoteone

More from Medium

Data protection laws may soon alter from GDPR

Mothers and Daughters

[26] I know nothing

Here Are Some of the Best Places to Ride a Citi Bike in South Brooklyn