remove a node from the middle of a linked list in typescript

To remove a node from the middle of a linked list in TypeScript, you need to perform the following steps:

  1. Traverse the linked list to find the node that needs to be removed
  2. Update the next property of the previous node to skip over the node that is being removed
  3. Set the next property of the node being removed to null

Here's an example implementation of a removeNode function for a singly linked list in TypeScript:

index.ts
class ListNode<T> {
  val: T;
  next?: ListNode<T>;
  constructor(val: T, next?: ListNode<T>) {
    this.val = val;
    this.next = next;
  }
}

function removeNode<T>(head: ListNode<T>, node: ListNode<T>): ListNode<T> | null {
  let prev: ListNode<T> | undefined;
  let curr: ListNode<T> | undefined = head;

  // Traverse the linked list to find the node to remove
  while (curr) {
    if (curr === node) {
      break;
    }
    prev = curr;
    curr = curr.next;
  }

  if (!curr) {
    // Node not found in linked list
    return head;
  }

  if (!prev) {
    // Removing first node in linked list
    return curr.next;
  }

  // Update previous node to skip over the node being removed
  prev.next = curr.next;

  // Set the next property of the node being removed to null
  curr.next = null;

  return head;
}
817 chars
41 lines

This implementation uses a ListNode class to represent nodes in the linked list. The removeNode function takes as input the head node of the linked list and the node to be removed. It returns the head node of the linked list after the removal operation.

The function traverses the linked list to find the node to be removed. If the node is not found, it simply returns the original head node. If the node is found, it checks if it is the first node in the linked list. If it is, it updates the head node to skip over the node being removed. If it is not the first node, it updates the next property of the previous node to skip over the node being removed. Finally, it sets the next property of the node being removed to null before returning the head node of the updated linked list.

gistlibby LogSnag