php链表

php链表

<?php
/**
 * Created by PhpStorm.
 * User: Alex
 * Date: 2019/5/13
 * Time: 13:35
 */

class Node
{
    public $data;
    public $next;

    public function __construct($data)
    {
        $this->data = $data;
        $this->next = null;
    }
}

class SingleLinkedList
{
    private $header;

    public function __construct($data)
    {
        $this->header = new Node($data);
    }

    public function addNode($data)
    {
        $newNode            = new Node($data);
        $newNode->next      = $this->header->next;
        $this->header->next = $newNode;
    }

    public function insertNode($item, $data)
    {
        $newNode = new Node($data);
        $current = $this->findNode($item);
        var_dump($current);
        $newNode->next = $current->next;
        $current->next = $newNode;
    }

    public function findNode($item)
    {
        $current = $this->header;
        while ($current->data != $item) {
            $current = $current->next;
        }

        return $current;
    }

    public function updateNode($old, $new)
    {
        $current = $this->header;

        if ($current->next == null) {
            return false;
        }

        while (!empty($current)) {
            echo "$current->data \n";
            if ($current->data == $old) {
                $current->data = $new;
                //$newNode       = new Node($new);
                //$newNode->next = $current->next;
                //$current->next = $newNode;

                break;
            }
            $current = $current->next;
        }
    }

    //public function deleteNode($item){
    //    $current = $this->header;
    //    $next = null;
    //    while (!empty($current)) {
    //        echo "$current->data \n";
    //        if ($current->next->data == $item) {
    //
    //            if ($current->next  != null) {
    //                $next = $current->next;
    //            }
    //            $current->next = $next;
    //
    //            break;
    //        }
    //        $current = $current->next;
    //    }
    //}
}

$linkedList = new SingleLinkedList('root');
//$linkedList->addNode('node1');
//$linkedList->addNode('node2');
//$linkedList->addNode('node3');
var_dump($linkedList);
$linkedList->insertNode('root', "node1");
$linkedList->insertNode('node1', "node2");
$linkedList->insertNode('root', "node0");

$res = $linkedList->updateNode('node2','node22');
var_dump($res);
var_dump($linkedList);