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

To remove a node from the beginning of a linked list in PHP, you need to follow these steps:

  1. Set the head of the linked list to be the next node in line.
  2. Unset the original head node.

Here is the code to accomplish this:

main.php
// define the Node class
class Node {
    public $data;
    public $next;
    
    public function __construct($data) {
        $this->data = $data;
        $this->next = null;
    }
}

// define the LinkedList class
class LinkedList {
    public $head;
    
    public function __construct() {
        $this->head = null;
    }
    
    public function removeFirst() {
        // if the list is empty, do nothing
        if ($this->head == null) {
            return;
        }
        
        // set the head to be the next node in line
        $this->head = $this->head->next;
        
        // unset the original head node
        unset($oldHead);
    }
}

// create a linked list and add some nodes
$list = new LinkedList();
$list->head = new Node(1);
$list->head->next = new Node(2);
$list->head->next->next = new Node(3);

// remove the first node
$list->removeFirst();
880 chars
42 lines

In this example, the removeFirst() method removes the first node (the node with data equal to 1) from the linked list.

gistlibby LogSnag