码迷,mamicode.com
首页 > 其他好文 > 详细

单项链表

时间:2019-12-24 09:40:48      阅读:64      评论:0      收藏:0      [点我收藏+]

标签:turn   添加   data   current   highlight   head   节点   value   each   

 class Node{
        public $data=null;
        public $next=null;
        public function __construct($data=null){
            $this->data = $data;
        }
    }
    class LinkNode{
        public $header=null;
        public function __construct(){
            $this->header = new Node();
        }
        //添加
        public function insert($data){
            $current = $this->header;
            while($current->next){
                $current=$current->next;
            }
            $current->next = new Node($data);
        }

        //遍历
        public function listLink(){
            $current = $this->header;
            while($current){
                echo $current->data;
                echo "\r\n";
                $current=$current->next;
            }
        }
        //通过数字返回节点所在位置
        public function find($data){
            $current = $this->header->next;
            $index=0;
            while($current){
                if($current->data == $data){
                    break;
                }
                $current = $current->next;
                $index++;

            }
            return $index;
        }

        //修改
        public function update($num,$data){
            $index=1;
            $current = $this->header;
            while($index <= $num){
                $prev=$current;
                $current=$current->next;
                $index++;
            }
            $current->data=$data;
        }

        //固定位置插入数字
        public function addData($num,$data){
            $current = $this->header->next;
            $index = 1;
            $node = new Node($data);
            while($index < $num){
                $prev = $current;
                $current=$current->next;
                $index++;
            }
            $prev->next=$node;
            $node->next=$current;
        }
        //清除数据
        public function delData($num){
            
        }
    }

    $arr=[10,304,4,5,1,30];
    $obj  = new LinkNode();
    foreach ($arr as $key => $value) {
        $obj->insert($value);
    }
    //$obj->addData(4,100);
    //$obj->update(2,9);
    //$obj->listLink();

  

单项链表

标签:turn   添加   data   current   highlight   head   节点   value   each   

原文地址:https://www.cnblogs.com/zh718594493/p/12089482.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!