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

To remove a node from the end of a linked list in php, we have to traverse through the linked list until we reach the second last node, and then delete the last node from the linked list.

Here's a sample code block that demonstrates the process:

main.php
class Node {
    public $data;
    public $next;
 
    function __construct($data) {
        $this->data = $data;
        $this->next = null;
    }
}
 
class LinkedList {
    private $head;
 
    public function __construct() {
        $this->head = null;
    }
 
    public function removeLastNode() {
        if ($this->head == null) return;
        if ($this->head->next == null) {
            $this->head = null;
            return;
        }
 
        $prev = null;
        $current = $this->head;
        while ($current->next != null) {
            $prev = $current;
            $current = $current->next;
        }
        $prev->next = null;
    }
}
659 chars
34 lines

In this code block, we first define the Node and LinkedList class. The LinkedList class has a reference to the head node of the linked list.

To remove the last node from the linked list, we first check if the linked list is empty or if it has only one node. If it has only one node, we make the head null.

If the linked list has more than one node, we traverse through the linked list until we reach the second last node. We then set its next pointer to null, thus removing the last node from the linked list.

To use this code, we can create a linked list and add some nodes to it, then call the removeLastNode() function to remove the last node.

main.php
$ll = new LinkedList();
$ll->head = new Node(1);
$ll->head->next = new Node(2);
$ll->head->next->next = new Node(3);

$ll->removeLastNode();

// The linked list should now be: 1 -> 2
183 chars
9 lines

gistlibby LogSnag