php如何实现链表?-PHP问题

资源魔 29 0

php完成链表的办法:起首界说一个节点类,代码为【function __construct($val=null)】;而后完成链表的完成类,代码为【function_construct $this->du妹妹yhead = new Nod】。

php完成链表的办法:

起首界说一个节点类

class Node{
    public $val;
    public $next;
    function __construct($val=null){
        $this->val = $val;
        $this->next = null;
    }
}

链表的完成类

class MyLinkedList {
    public $du妹妹yhead; //界说一个虚构的头结点
    public $size;
  
    function __construct() {
        $this->du妹妹yhead = new Node(); 
        $this->size = 0;
    }
  
 
    function get($index) {
        if($index < 0 || $index >= $this->size)
            return -1;
        $cur = $this->du妹妹yhead;
        for($i = 0; $i < $index; $i++){
            $cur = $cur->next;
        }
        return $cur->next->val;
    }
  
    function addAtHead($val) {
        $this->addAtIndex(0,$val);
    }
  
  
    function addAtTail($val) {
        $this->addAtIndex($this->size,$val);
    }
  
    function addAtIndex($index, $val) {
        if($index < 0 || $index > $this->size)
            return;
        $cur = $this->du妹妹yhead;
        for($i = 0; $i < $index; $i++){
            $cur = $cur->next;
        }
        $node = new Node($val);
        $node->next = $cur->next;
        $cur->next = $node;
        $this->size++;
    }
  
    function deleteAtIndex($index) {
        if($index < 0 || $index >= $this->size)
            return;
        $cur = $this->du妹妹yhead;
        for($i = 0; $i < $index; $i++){
            $cur = $cur->next;
        }
        $cur->next = $cur->next->next;
        $this->size--;
    }
}

相干学习保举:PHP编程从入门到通晓

以上就是php若何完成链表?的具体内容,更多请存眷资源魔其它相干文章!

标签: php php教程 链表 php故障解决 php使用问题

抱歉,评论功能暂时关闭!