Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare the head of a doubly linked list.
DSA Java
Node [1];Attempts:
3 left
💡 Hint
Common Mistakes
Using 'next' or 'prev' as the list head variable.
Using 'tail' instead of 'head' for the start of the list.
✗ Incorrect
The head is the starting node of a doubly linked list, so we declare it as 'head'.
2fill in blank
mediumComplete the constructor to initialize a new node with given data.
DSA Java
public Node(int data) {
this.data = data;
this.[1] = null;
this.prev = null;
}Attempts:
3 left
💡 Hint
Common Mistakes
Initializing 'prev' twice instead of 'next'.
Using 'head' or 'tail' inside the node constructor.
✗ Incorrect
The 'next' pointer should be initialized to null in the node constructor.
3fill in blank
hardFix the error in the method that adds a new node at the beginning of the doubly linked list.
DSA Java
public void addFirst(int data) {
Node newNode = new Node(data);
newNode.next = head;
if (head != null) {
head.[1] = newNode;
}
head = newNode;
}Attempts:
3 left
💡 Hint
Common Mistakes
Setting 'next' instead of 'prev' for the old head.
Forgetting to update the old head's pointer.
✗ Incorrect
When adding at the front, the old head's 'prev' should point back to the new node.
4fill in blank
hardFill both blanks to complete the method that adds a new node at the end of the doubly linked list.
DSA Java
public void addLast(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
return;
}
Node temp = head;
while (temp.[1] != null) {
temp = temp.[2];
}
temp.next = newNode;
newNode.prev = temp;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'prev' to traverse forward, which is incorrect.
Using 'head' or 'tail' inside the loop incorrectly.
✗ Incorrect
To reach the last node, we follow 'next' pointers until null is found.
5fill in blank
hardFill both blanks to complete the method that prints the doubly linked list from head to tail.
DSA Java
public void printList() {
Node temp = head;
while (temp != null) {
System.out.print(temp.[1] + " <-> ");
temp = temp.[2];
}
System.out.println("null");
}Attempts:
3 left
💡 Hint
Common Mistakes
Printing 'next' or 'prev' instead of 'data'.
Moving backward using 'prev' instead of forward using 'next'.
✗ Incorrect
We print the 'data' of each node and move forward using 'next'.
