php實作鍊錶的方法:先定義一個節點類,程式碼為【function __construct($val=null)】;然後實作鍊錶的實作類,程式碼為【function addAtIndex($index, $val) 】。
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中文網其他相關文章!