-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQueueAsLinkedList.java
100 lines (79 loc) · 2.48 KB
/
QueueAsLinkedList.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
class Node {
int data;
Node next;
// Constructor to initialize a node
Node(int data) {
this.data = data;
this.next = null;
}
}
class QueueAsLinkedList {
Node front, rear;
// Constructor to initialize an empty queue
QueueAsLinkedList() {
this.front = this.rear = null;
}
// Method to check if the queue is empty
public boolean isEmpty() {
return front == null;
}
// Method to add an element to the queue
public void enqueue(int data) {
Node newNode = new Node(data);
// If the queue is empty, then the new node becomes both the front and rear
if (rear == null) {
front = rear = newNode;
System.out.println(data + " enqueued to queue");
return;
}
// Add the new node at the end of the queue and change the rear
rear.next = newNode;
rear = newNode;
System.out.println(data + " enqueued to queue");
}
// Method to remove an element from the queue
public int dequeue() {
if (isEmpty()) {
System.out.println("Queue is empty");
return Integer.MIN_VALUE;
}
int dequeued = front.data;
front = front.next;
// If the front becomes null, then change rear to null
if (front == null) {
rear = null;
}
return dequeued;
}
// Method to get the front element of the queue
public int peek() {
if (isEmpty()) {
System.out.println("Queue is empty");
return Integer.MIN_VALUE;
}
return front.data;
}
// Method to print the queue elements
public void printQueue() {
if (isEmpty()) {
System.out.println("Queue is empty");
return;
}
Node currentNode = front;
while (currentNode != null) {
System.out.print(currentNode.data + " ");
currentNode = currentNode.next;
}
System.out.println();
}
public static void main(String[] args) {
QueueAsLinkedList queue = new QueueAsLinkedList();
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
queue.printQueue(); // Output: 10 20 30
System.out.println(queue.dequeue() + " dequeued from queue"); // Output: 10 dequeued from queue
queue.printQueue(); // Output: 20 30
System.out.println("Front element is " + queue.peek()); // Output: Front element is 20
}
}