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

To remove a node from the middle of a linked list in PHP, you have to do the following steps:

  • Traverse the linked list until you find the node that needs to be removed (let's call it $node_to_remove)
  • Update the previous node's next pointer to skip over $node_to_remove
  • Free $node_to_remove from memory

Here's the PHP code for removing a node from the middle of a linked list:

main.php
function removeNode($head, $node_to_remove) {
    $prev_node = null;
    $curr_node = $head;

    // Traverse the linked list until we find $node_to_remove
    while ($curr_node != null && $curr_node != $node_to_remove) {
        $prev_node = $curr_node;
        $curr_node = $curr_node->next;
    }

    // If $node_to_remove is not found, return the original head node
    if ($curr_node == null) {
        return $head;
    }

    // If $node_to_remove is the head node, update $head to point to the next node
    if ($prev_node == null) {
        $head = $curr_node->next;
    } else {
        // Otherwise, update the previous node's next pointer to skip over $node_to_remove
        $prev_node->next = $curr_node->next;
    }

    // Free $node_to_remove from memory
    unset($node_to_remove);

    return $head;
}
822 chars
29 lines

Note that this code assumes that each node in the linked list has a next pointer pointing to the next node in the list. Also, it's important to free the memory occupied by the removed node to avoid memory leaks.

gistlibby LogSnag