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编程从入门到精通
以上就是php如何实现链表?的详细内容,更多请关注php中文网其它相关文章!
已抢111504个
抢已抢47352个
抢已抢133951个
抢已抢32511个
抢已抢467个
抢已抢1059个
抢