Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to add a new node at the end of the queue.
DSA Java
public void enqueue(int data) {
Node newNode = new Node(data);
if (rear == null) {
front = rear = newNode;
return;
}
rear.[1] = newNode;
rear = newNode;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'prev' instead of 'next' pointer.
Trying to assign data instead of linking nodes.
✗ Incorrect
The 'next' pointer of the current rear node should point to the new node to add it at the end.
2fill in blank
mediumComplete the code to remove the front node from the queue.
DSA Java
public int dequeue() {
if (front == null) {
throw new NoSuchElementException("Queue is empty");
}
int value = front.data;
front = front.[1];
if (front == null) {
rear = null;
}
return value;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'prev' pointer which does not exist in singly linked list.
Not updating rear when queue becomes empty.
✗ Incorrect
To remove the front node, move the front pointer to the next node.
3fill in blank
hardFix the error in the method that checks if the queue is empty.
DSA Java
public boolean isEmpty() {
return [1] == null;
}Attempts:
3 left
💡 Hint
Common Mistakes
Checking rear instead of front.
Checking data or next which are not pointers to nodes.
✗ Incorrect
The queue is empty if the front pointer is null.
4fill in blank
hardFill both blanks to implement a method that returns the front element without removing it.
DSA Java
public int peek() {
if ([1] == null) {
throw new NoSuchElementException("Queue is empty");
}
return [2].data;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using rear instead of front.
Trying to access data from next pointer.
✗ Incorrect
The peek method checks if front is null and returns front.data to see the first element.
5fill in blank
hardFill all three blanks to implement a method that prints all elements in the queue.
DSA Java
public void printQueue() {
Node current = [1];
while (current != [2]) {
System.out.print(current.[3] + " -> ");
current = current.next;
}
System.out.println("null");
}Attempts:
3 left
💡 Hint
Common Mistakes
Using rear as loop end condition.
Printing current.next instead of current.data.
✗ Incorrect
Start from front, loop until current is null, print current.data each time.
