首頁  >  文章  >  後端開發  >  php如何實作鍊錶?

php如何實作鍊錶?

coldplay.xixi
coldplay.xixi原創
2020-07-10 16:30:242409瀏覽

php實作鍊錶的方法:先定義一個節點類,程式碼為【function __construct($val=null)】;然後實作鍊錶的實作類,程式碼為【function_construct $this->dummyhead = new Nod】。

php如何實作鍊錶?

php實作鍊錶的方法:

先定義一個節點類別

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

鍊錶的實作類別

class MyLinkedList {
    public $dummyhead; //定义一个虚拟的头结点
    public $size;
  
    function __construct() {
        $this->dummyhead = new Node(); 
        $this->size = 0;
    }
  
 
    function get($index) {
        if($index < 0 || $index >= $this->size)
            return -1;
        $cur = $this->dummyhead;
        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->dummyhead;
        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->dummyhead;
        for($i = 0; $i < $index; $i++){
            $cur = $cur->next;
        }
        $cur->next = $cur->next->next;
        $this->size--;
    }
}

相關學習推薦:PHP程式設計從入門到精通

以上是php如何實作鍊錶?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn