php怎么样实现链表?,链表,定义,节点,代码,方法
php怎么样实现链表?
易采站长站,站长之家为您整理了php怎么样实现链表?的相关内容。
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怎么样实现链表?内容提出宝贵意见