remove a node from the end of a linked list in javascript

To remove a node from the end of a linked list in JavaScript, we need to traverse the entire linked list till we reach the end.

Once we reach the end, we can simply remove the node from the linked list by setting the next pointer of the second-last node to null.

Here's the JavaScript code to remove a node from the end of a linked list:

index.tsx
function removeLastNode(head) {
  if (!head || !head.next) {
    // Head is null or only 1 node in the list
    return null; 
  }
  let curr = head;
  while (curr.next.next) {
    // Traverse till the end of the list
    curr = curr.next;
  }
  // Now `curr` points to the second-last node
  curr.next = null; // Remove the last node
  return head;
}
351 chars
15 lines

The above code checks if there are at least 2 nodes in the linked list. If yes, it traverses till the end of the list while keeping track of the second-last node using the curr variable.

Finally, it sets the next pointer of the second-last node to null to remove the last node.

Note that this code assumes that the linked list is singly linked. If the linked list is doubly linked, you would also need to update the prev pointer of the last node.

gistlibby LogSnag