Implement Linked List Operations - Implement Linked List Operations

Tell us what’s happening:

My current answer to the getAt function does not check out. I have removed the functions after that one as I have yet to build them.

So the idea I’ve got for this function is to define the current of the list and an index i to iterate through the list, from head to tail. This loop is supposed to return the current element if the given index has been found, otherwise it moves to the next element. If the given index is outside of the list, it returns undefined.

I’m not sure where the error lies at, but it could be the return current line. Can you help me understand what’s wrong with this? Thank you.

Your code so far

function initList() {
  return {
    head: null,
    length: 0
  };
}

function isEmpty(list) {
  return list.length === 0;
}

function add(list, element) {
  const node = { element, next: null };

  if (isEmpty(list)) {
    list.head = node;
  } else {
    let current = list.head;
    while (current.next !== null) {
      current = current.next;
    }
    current.next = node;
  }

  list.length++;
}

function remove(list, element) {
  let previous = null;
  let current = list.head;

  while (current !== null && current.element !== element) {
    previous = current;
    current = current.next;
  }

  if (current === null) return;

  if (previous !== null) {
    previous.next = current.next;
  } else {
    list.head = current.next;
  }

  list.length--;
}

function contains(list, element) {
  let current = list.head;

  while (current !== null) {
    if (current.element === element) {
      return true;
    }
    current = current.next;
  }
  return false;
} 

function getAt(list, index) {
  let current = list.head;
  let i = 0;
    
  while (current) {
    if (i === index) {
      return current
    }
    i++;
    current = current.next;
  }
  return undefined;
}


Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64; rv:150.0) Gecko/20100101 Firefox/150.0

Challenge Information:

Implement Linked List Operations - Implement Linked List Operations

hello!

The test actually requires you to return the element from the node in the given index in the getAt function. You are currently returning the node itself.

Ah, so that line was incomplete. Thank you, that let me resolve test 9.

(I can’t edit the previous post, or I haven’t found how to?)

Thank you, I’ve managed to solve the entire challenge from here.