Tell us what’s happening:
- clear should remove all elements from the list.
Your code so far
// Node constructor
function Node(value) {
this.value = value;
this.next = null;
}
// 1. initList
function initList() {
return {
head: null,
length: 0
};
}
// 2. add
function add(list, element) {
const newNode = new Node(element);
if (!list.head) {
list.head = newNode;
} else {
let current = list.head;
while (current.next) {
current = current.next;
}
current.next = newNode;
}
list.length++;
}
// 3. remove (fixed)
function remove(list, element) {
if (!list.head) return;
let current = list.head;
let previous = null;
while (current) {
if (current.value === element) {
if (previous === null) {
list.head = current.next;
} else {
previous.next = current.next;
}
list.length--; // ✅ always decrease
return;
}
previous = current;
current = current.next;
}
}
// 4. contains
function contains(list, element) {
let current = list.head;
while (current) {
if (current.value === element) return true;
current = current.next;
}
return false;
}
// 5. getAt
function getAt(list, index) {
if (index < 0 || index >= list.length) return undefined;
let current = list.head;
let i = 0;
while (i < index) {
current = current.next;
i++;
}
return current.value;
}
// 6. insertAt
function insertAt(list, index, element) {
if (index < 0 || index > list.length) return;
const newNode = new Node(element);
if (index === 0) {
newNode.next = list.head;
list.head = newNode;
list.length++;
return;
}
let current = list.head;
let i = 0;
while (i < index - 1) {
current = current.next;
i++;
}
newNode.next = current.next;
current.next = newNode;
list.length++;
}
// 7. removeAt (fixed)
function removeAt(list, index) {
if (index < 0 || index >= list.length) return;
// ✅ explicit single element case
if (list.length === 1 && index === 0) {
list.head = null;
list.length = 0;
return;
}
// remove first
if (index === 0) {
list.head = list.head.next;
list.length--;
return;
}
let current = list.head;
let i = 0;
while (i < index - 1) {
current = current.next;
i++;
}
current.next = current.next.next;
list.length--;
}
// 8. clear (fixed)
function clear(list) {
list.head = null;
list.length = 0;
}
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36
Challenge Information:
Implement Linked List Operations - Implement Linked List Operations