Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a node class for the circular singly linked list.
DSA Java
class Node { int data; Node next; Node(int data) { this.data = data; this.[1] = null; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'prev' which is for doubly linked lists.
Using 'head' or 'tail' inside the node class.
✗ Incorrect
The 'next' pointer in a node points to the next node in the list. Initializing it to null is standard.
2fill in blank
mediumComplete the code to initialize the circular singly linked list with a single node pointing to itself.
DSA Java
public class CircularSinglyLinkedList { Node head; public CircularSinglyLinkedList(int data) { head = new Node(data); head.[1] = head; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Setting next to null instead of pointing to itself.
Using wrong pointer names like 'prev'.
✗ Incorrect
In a circular singly linked list with one node, the node's next points to itself.
3fill in blank
hardFix the error in the add method to correctly insert a new node at the end of the circular singly linked list.
DSA Java
public void add(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
newNode.next = newNode;
} else {
Node temp = head;
while (temp.[1] != head) {
temp = temp.next;
}
temp.next = newNode;
newNode.next = head;
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'prev' which does not exist in singly linked list.
Using 'head' as a pointer inside the loop condition.
✗ Incorrect
To find the last node, we traverse using the 'next' pointer until we reach the head again.
4fill in blank
hardFill both blanks to complete the method that prints all elements in the circular singly linked list.
DSA Java
public void printList() {
if (head == null) {
System.out.println("List is empty");
return;
}
Node temp = head;
do {
System.out.print(temp.[1] + " -> ");
temp = temp.[2];
} while (temp != head);
System.out.println("null");
}Attempts:
3 left
💡 Hint
Common Mistakes
Trying to print 'next' instead of 'data'.
Using 'prev' which does not exist.
✗ Incorrect
To print the data, access 'data'. To move forward, use 'next'.
5fill in blank
hardFill all three blanks to complete the method that deletes the node with given data from the circular singly linked list.
DSA Java
public void delete(int key) {
if (head == null) return;
Node current = head, prev = null;
do {
if (current.[1] == key) {
if (prev != null) {
prev.[2] = current.[3];
} else {
// Deleting head node
Node temp = head;
while (temp.next != head) {
temp = temp.next;
}
if (head.next == head) {
head = null;
} else {
temp.next = head.next;
head = head.next;
}
}
return;
}
prev = current;
current = current.next;
} while (current != head);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'prev' instead of 'next' for pointers.
Not handling deletion of the head node correctly.
✗ Incorrect
We compare 'data' to key, update 'prev.next' to 'current.next' to remove the node.
