Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a simple Node class for a linked list.
DSA Java
class Node { int data; Node [1]; Node(int data) { this.data = data; this.next = 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' field points to the next node in the linked list.
2fill in blank
mediumComplete the code to initialize the slow pointer to the head of the linked list.
DSA Java
Node slow = [1];Attempts:
3 left
💡 Hint
Common Mistakes
Initializing slow to null or tail.
Using 'next' which is a field, not a variable.
✗ Incorrect
The slow pointer starts at the head of the linked list.
3fill in blank
hardFix the error in the while loop condition to avoid NullPointerException when finding the middle node.
DSA Java
while (fast != null && fast.[1] != null) { slow = slow.next; fast = fast.next.next; }
Attempts:
3 left
💡 Hint
Common Mistakes
Checking fast.prev which does not exist in singly linked list.
Not checking fast.next leading to NullPointerException.
✗ Incorrect
We check fast.next to ensure fast.next.next is safe to access.
4fill in blank
hardFill both blanks to complete the method that returns the middle node's data.
DSA Java
public int findMiddle(Node [1]) { Node slow = [1]; Node fast = [1]; while (fast != null && fast.[2] != null) { slow = slow.next; fast = fast.next.next; } return slow.data; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'head' inside the method instead of the parameter.
Checking fast.prev which is invalid.
✗ Incorrect
The method parameter is 'node' but inside the method 'head' should be replaced with 'node' to use the passed list. The loop checks fast.next.
5fill in blank
hardFill all three blanks to complete the main method that creates a linked list and prints its middle element.
DSA Java
public static void main(String[] args) {
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);
[1] finder = new [2]();
int middle = finder.[3](head);
System.out.println("Middle element: " + middle);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong class names or method names.
Calling method on class instead of instance.
✗ Incorrect
The class name is 'FindMiddleElement' and the method to find middle is 'findMiddle'.
