Linked List Insert Tail

Append a new node to the tail of a singly linked list by traversing to the final node.

Time O(n) Space O(n) Singly Linked List insertTail

How it works

Append a new node to the tail of a singly linked list by traversing to the final node.

Implementation

function sllInsertTailOp(state, value) {
  const valueArr = state.value;
  const next = state.next;
  const id = valueArr.length;
  valueArr[id] = value;
  next[id] = -1;
  insertNode(id, value);
  if (state.head === -1) {
    state.head = id;
    finish(id);
    return;
  }
  let current = state.head;
  while (next[current] !== -1) {
    visitNode(current);
    current = next[current];
  }
  next[current] = id;
  linkNodes(current, id);
  finish(id);
}