forked from IamBisrutPyne/Java-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueue.java
More file actions
76 lines (64 loc) · 1.73 KB
/
Queue.java
File metadata and controls
76 lines (64 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/**
* Program Title: Queue (Linked List Implementation)
* Author: [Ahad-23]
* Date: 2025-10-08
*
* Description: Implements a generic Queue data structure using a custom
* Singly Linked List. Operations (enqueue, dequeue, peek) are designed
* to adhere to the FIFO (First-In, First-Out) principle.
*
* Time Complexity: O(1) for all main operations (enqueue, dequeue, peek).
* Space Complexity: O(N) where N is the number of elements stored.
*/
public class Queue<T> {
// Node class for custom singly linked list
private static class Node<T> {
T data;
Node<T> next;
Node(T data) {
this.data = data;
this.next = null;
}
}
private Node<T> front;
private Node<T> rear;
private int size;
public Queue() {
this.front = null;
this.rear = null;
this.size = 0;
}
public void enqueue(T data) {
Node<T> newNode = new Node<>(data);
if (rear == null) front = rear = newNode;
else
{
rear.next = newNode;
rear = newNode;
}
size++;
}
public T dequeue() {
if (isEmpty()) {
throw new NoSuchElementException("Queue is empty. Cannot dequeue.");
}
T value = front.data;
front = front.next;
if (front == null) rear = null;
size--;
return value;
}
public T peek() {
if (isEmpty()) {
throw new NoSuchElementException("Queue is empty. Cannot dequeue.");
}
return front.data;
}
public boolean isEmpty() {
return front == null;
}
// Get current size of the queue
public int size() {
return size;
}
}