php實現連結串列的方法:首先定義一個節點類,程式碼為【function __construct($val=null)】;然後實現連結串列的實現類,程式碼為【function_construct $this->dummyhead = new Nod】。
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如何實現連結串列?的詳細內容,更多請關注TW511.COM其它相關文章!