Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare the previous node pointer in a doubly linked list node.
DSA C#
public class Node { public int data; public Node next; public Node [1]; public Node(int data) { this.data = data; this.next = null; this.[1] = null; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'previousNode' or 'last' which are not standard names.
Using 'prior' which is uncommon.
✗ Incorrect
In a doubly linked list node, the pointer to the previous node is commonly named 'prev'.
2fill in blank
mediumComplete the constructor to initialize the previous pointer to null.
DSA C#
public Node(int data) {
this.data = data;
this.next = null;
this.[1] = null;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using a different variable name than declared.
Forgetting to initialize the previous pointer.
✗ Incorrect
The previous pointer is named 'prev' and should be initialized to null in the constructor.
3fill in blank
hardFix the error in the method that adds a new node at the end of the doubly linked list by completing the missing assignment.
DSA C#
public void AddLast(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
newNode.[1] = current;
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using an incorrect pointer name.
Not setting the previous pointer at all.
✗ Incorrect
The new node's previous pointer should be set to the current last node using 'prev'.
4fill in blank
hardFill both blanks to correctly update pointers when inserting a new node after a given node in a doubly linked list.
DSA C#
public void InsertAfter(Node node, int data) {
if (node == null) return;
Node newNode = new Node(data);
newNode.next = node.[1];
newNode.[2] = node;
node.next = newNode;
if (newNode.next != null) {
newNode.next.prev = newNode;
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up next and prev pointers.
Not updating the surrounding nodes' pointers correctly.
✗ Incorrect
The new node's next pointer is set to the current node's next, and its prev pointer is set to the current node.
5fill in blank
hardFill all three blanks to correctly remove a node from a doubly linked list by updating the surrounding nodes' pointers.
DSA C#
public void Remove(Node node) {
if (node == null) return;
if (node.prev != null) {
node.prev.[1] = node.[2];
} else {
head = node.[3];
}
if (node.next != null) {
node.next.prev = node.prev;
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Confusing prev and next pointers during removal.
Not updating the head when removing the first node.
✗ Incorrect
The previous node's next pointer is set to the node's next, the head is updated to node's next if node.prev is null, and the node's next pointer is used accordingly.
