zoukankan      html  css  js  c++  java
  • 链表练习 链表反转 链表插入..

    <?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();
  • 相关阅读:
    优化--工具
    架构
    Gradle
    战争迷雾
    进度管理
    工具
    架构
    牛人
    apk 破解
    效率
  • 原文地址:https://www.cnblogs.com/guiyishanren/p/11871710.html
Copyright © 2011-2022 走看看