SoFunction
Updated on 2025-03-10

PHP implementation of single linked list example code

//Construction method
    public function __construct($id = null, $name = null) {
        $this->header = new node ( $id, $name, null );
    }

//Get the length of the linked list
    public function getLinkLength() {
        $i = 0;
        $current = $this->header;
        while ( $current->next != null ) {
            $i ++;
            $current = $current->next;
        }
        return $i;
    }

//Add node data
    public function addLink($node) {
        $current = $this->header;
        while ( $current->next != null ) {
            if ($current->next->id > $node->id) {
                break;
            }
            $current = $current->next;
        }
        $node->next = $current->next;
        $current->next = $node;
    }

//Delete the linked list node
    public function delLink($id) {
        $current = $this->header;
        $flag = false;
        while ( $current->next != null ) {
            if ($current->next->id == $id) {
                $flag = true;
                break;
            }
            $current = $current->next;
        }
        if ($flag) {
            $current->next = $current->next->next;
        } else {
echo "Node not found!<br>";
        }
    }

//Get the link list
    public function getLinkList() {
        $current = $this->header;
        if ($current->next == null) {
echo ("Link list is empty!");
            return;
        }
        while ( $current->next != null ) {
            echo 'id:' . $current->next->id . '   name:' . $current->next->name . "<br>";
            if ($current->next->next == null) {
                break;
            }
            $current = $current->next;
        }
    }

//Get the node name
    public function getLinkNameById($id) {
        $current = $this->header;
        if ($current->next == null) {
echo "The link list is empty!";
            return;
        }
        while ( $current->next != null ) {
            if ($current->id == $id) {
                break;
            }
            $current = $current->next;
        }
        return $current->name;
    }

//Update the node name
    public function updateLink($id, $name) {
        $current = $this->header;
        if ($current->next == null) {
echo "The link list is empty!";
            return;
        }
        while ( $current->next != null ) {
            if ($current->id == $id) {
                break;
            }
            $current = $current->next;
        }
        return $current->name = $name;
    }
}