Msc:Mphil GROUP 4 Queue
Msc:Mphil GROUP 4 Queue
1. Introduction
A queue is a linear data structure that follows the First-In-First-Out (FIFO) principle,
where elements are added (enqueued) at the end and removed (dequeued) from the
front. Implementing a queue using a singly linked list provides flexibility in memory
allocation and ensures efficient operations.
2. Implementation
Node.java Class
public class Node {
int data; // Data stored in the node
Node next; // Reference to the next node in the list
Queue.java Class
// Queue class using a singly linked list
public class Queue {
private Node front, rear; // Pointers to the front and rear of the queue
private int size; // Number of elements in the queue
public Queue() {
this.front = this.rear = null; // Initially, both front and rear are null
this.size = 0;
}
// If the queue is empty, the new node becomes both the front and rear
if (this.rear == null) {
this.front = this.rear = newNodes;
} else {
this.rear.next = newNodes; // Link the new node at the end of the queue
this.rear = newNodes; // Update the rear pointer
}
size++;
}
// Dequeue operation - Removes and returns the front element of the queue
public int dequeue() {
if (isEmpty()) {
throw new IllegalStateException("Queue is empty");
}
int data = this.front.data; // Get the data from the front node
this.front = this.front.next; // Move the front pointer to the next node
App.java Class
public class App {
public static void main(String[] args) {
// Create a Queue instance
Queue queue = new Queue();
3. Explanation
● Node Class: Represents each element in the queue. Each node contains
data and a reference (next) to the next node in the list.
● Queue Class: Manages the queue using two pointers, front and rear, to keep
track of the front and rear of the queue, respectively.
○ enqueue: Adds a new element to the rear of the queue. If the queue is
empty, the new node becomes both the front and rear. Otherwise, it
links the new node to the rear and updates the rear pointer.
○ dequeue: Removes and returns the front element of the queue. The
front pointer is updated to the next node. If the queue becomes empty,
the rear pointer is set to null.
○ isEmpty: Returns true if the queue has no elements; otherwise, false.
○ size: Returns the number of elements in the queue
● Challenges:
○ Memory Usage: Each element requires extra memory for the pointer
(next), leading to higher memory consumption compared to arrays.
○ Complexity: Linked list implementation is slightly more complex due to
pointer management.
● Benefits:
○ Dynamic Size: Unlike arrays, linked lists do not require a fixed size,
allowing the queue to grow and shrink as needed without reallocating
memory.
○ Efficient Operations: Both enqueue and dequeue operations are
efficient (O(1)) because no shifting of elements is required, as would be
the case in an array-based implementation.
6. Conclusion