php method to implement a linked list: first define a node class, the code is [function __construct($val=null)]; then implement the implementation class of the linked list, the code is [function_construct $this->dummyhead = new Nod].
php method to implement linked list:
First define a node class
class Node{ public $val; public $next; function __construct($val=null){ $this->val = $val; $this->next = null; } }
Implementation class of linked list
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--; } }
Related learning recommendations:PHP programming from entry to proficiency
The above is the detailed content of How to implement linked list in php?. For more information, please follow other related articles on the PHP Chinese website!