Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to add a new node at the end of a singly linked list.
DSA Javascript
function appendNode(head, value) {
let newNode = { data: value, next: null };
if (!head) return newNode;
let current = head;
while (current.[1] !== null) {
current = current.next;
}
current.next = newNode;
return head;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'prev' instead of 'next' to traverse the list.
Trying to access 'data' to move to the next node.
✗ Incorrect
In a singly linked list, each node points to the next node using the 'next' property. To traverse to the end, we check 'current.next'.
2fill in blank
mediumComplete the code to insert a new node before a given node in a doubly linked list.
DSA Javascript
function insertBefore(node, value) {
let newNode = { data: value, prev: null, next: null };
newNode.next = node;
newNode.[1] = node.prev;
if (node.prev) {
node.prev.next = newNode;
}
node.prev = newNode;
return newNode;
}Attempts:
3 left
💡 Hint
Common Mistakes
Setting newNode.next instead of newNode.prev.
Not updating node.prev to newNode.
✗ Incorrect
In a doubly linked list, each node has 'prev' and 'next'. To insert before, set newNode.prev to node.prev.
3fill in blank
hardFix the error in the code to correctly remove a node from a doubly linked list.
DSA Javascript
function removeNode(node) {
if (node.prev) {
node.prev.next = node.[1];
}
if (node.next) {
node.next.prev = node.prev;
}
node.prev = null;
node.next = null;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'prev' instead of 'next' when updating node.prev.next.
Not clearing node.prev and node.next after removal.
✗ Incorrect
To remove a node, link its previous node's 'next' to its next node.
4fill in blank
hardFill both blanks to create a function that traverses a doubly linked list backwards from tail to head.
DSA Javascript
function traverseBackward(tail) {
let current = tail;
while (current !== null) {
console.log(current.data);
current = current.[1];
}
}
// To start from tail, find tail by moving from head
function findTail(head) {
let current = head;
while (current.[2] !== null) {
current = current.next;
}
return current;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'next' to traverse backward.
Using 'prev' to find tail from head.
✗ Incorrect
To move backward, use 'prev'. To find tail from head, move forward using 'next'.
5fill in blank
hardFill all three blanks to create a function that converts a singly linked list to a doubly linked list.
DSA Javascript
function convertToDoubly(head) {
let current = head;
let prev = null;
while (current !== null) {
current.[1] = prev;
let nextNode = current.[2];
current.[3] = nextNode;
prev = current;
current = nextNode;
}
return head;
}Attempts:
3 left
💡 Hint
Common Mistakes
Confusing 'prev' and 'next' pointers.
Not updating 'prev' variable inside the loop.
✗ Incorrect
To convert, add 'prev' pointer to current node, keep 'next' pointer intact.
