-
Notifications
You must be signed in to change notification settings - Fork 0
/
Implementation of Queue using LinkedList.java
70 lines (63 loc) · 1.59 KB
/
Implementation of Queue using LinkedList.java
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
class Queue<T> {
private Node<T> front;
private Node<T> rear;
//Hello
// Inner class to represent a linked list node
private static class Node<T> {
T data;
Node<T> next;
Node(T data) {
this.data = data;
this.next = null;
}
}
// Constructor to initialize the queue
public Queue() {
front = null;
rear = null;
}
// Check if the queue is empty
public boolean isEmpty() {
return front == null;
}
// Get the size of the queue
public int size() {
int count = 0;
Node<T> current = front;
while (current != null) {
count++;
current = current.next;
}
return count;
}
// Add an element to the rear of the queue
public void enqueue(T data) {
Node<T> newNode = new Node<>(data);
if (isEmpty()) {
front = newNode;
rear = newNode;
} else {
rear.next = newNode;
rear = newNode;
}
}
// Remove and return an element from the front of the queue
public T dequeue() {
if (isEmpty()) {
throw new IllegalStateException("Queue is empty");
}
T data = front.data;
front = front.next;
if (front == null) {
rear = null;
}
return data;
}
// Peek at the element at the front of the queue without removing it
public T peek() {
if (isEmpty()) {
throw new IllegalStateException("Queue is empty");
}
return front.data;
}
}