Complete the code to check if the circular linked list is empty before deletion.
if (head === [1]) { return null; }
In a circular linked list, an empty list is represented by null. So, we check if head === null to know if the list is empty.
Complete the code to find the last node in the circular linked list.
let current = head; while (current.next !== [1]) { current = current.next; }
The last node in a circular linked list points back to the head. So, we loop until current.next === head.
Fix the error in updating the head when deleting the head node.
if (head.value === key) { last.next = [1]; head = [1]; return head; }
When deleting the head node, the last node's next should point to the new head, which is head.next. Then update head to head.next.
Fill both blanks to delete a node with a given key inside the circular linked list.
let current = head; while (current.next !== head && current.next.value !== [1]) { current = current.next; } if (current.next.value === [2]) { current.next = current.next.next; }
We look for the node whose next node has the value equal to the key. Then we skip that node by linking current.next to current.next.next.
Fill all three blanks to complete the delete function for a circular linked list.
function deleteNode(head: Node | null, key: number): Node | null {
if (head === [1]) return null;
let last = head;
while (last.next !== head) {
last = last.next;
}
if (head.value === key) {
last.next = [2];
head = [3];
return head;
}
let current = head;
while (current.next !== head && current.next.value !== key) {
current = current.next;
}
if (current.next.value === key) {
current.next = current.next.next;
}
return head;
}The function first checks if the list is empty (null). Then it finds the last node. If the head node has the key, it updates last.next to head.next and moves head to head.next. Otherwise, it searches for the node to delete and removes it by skipping it.
