链表练习 链表反转 链表插入..

<?php
class ListNode {
    public $data = null;
    public $next = null;
    public function __construct(string $data = NULL) {
        $this->data = $data;
        var_dump($this->data) . '</br>';
    }
}
class LinkedList{
    private $_firstNode = null;
    private $_totalNode = null;
    public function insert(string $data = null) {
        $newNode = new ListNode($data);
        if($this->_firstNode == null)
        {
            $this->_firstNode = &$newNode;
        }else{
            $currentNode = $this->_firstNode;
            while($currentNode->next !== null)
            {
                $currentNode = $currentNode->next;
            }
            $currentNode->next = $newNode;
        }
        $this->_totalNode++;
        return true;

    }
    public function display() {
        echo "链表长度为:" . $this->_totalNode;
        $currentNode = $this->_firstNode;
        while($currentNode !== null){
            echo "链表元素:</br>" . $currentNode->data . '</br>';
            $currentNode = $currentNode->next;
        }
    }
    /**
     *链表反转
     */
    public function reverse() {
        if($this->_firstNode != null){
            if($this->_firstNode->next !== null)
            {
                $reservedLinked = null;
                $next = null;
                $currentNode = $this->_firstNode;
                while($currentNode !== null)
                {
                    $next = $currentNode->next;
                    $currentNode->next = $reservedLinked;
                    $reservedLinked = $currentNode;
                    $currentNode = $next;
                }
                $this->_firstNode = $reservedLinked;
            }
        }
    }
}
$link_list = new LinkedList();
$link_list->insert(0);
$link_list->insert(1);
$link_list->insert(2);

$link_list->display();
echo "链表反转: </br>";
$link_list->reverse();
$link_list->display();

 

posted @ 2019-11-16 14:27  归一山人  阅读(170)  评论(0编辑  收藏  举报