发布网友 发布时间:2022-04-06 06:48
共2个回答
懂视网 时间:2022-04-06 11:10
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编程从入门到精通
热心网友 时间:2022-04-06 08:18
p是要删除的结点,q是p的前一个结点 q->next = p->next;//删除的结点的后一结点的首地址赋值给删除的结点的前一结点的next p->next->prior = q;//删除的结点的后一结点的prior指向删除的结点的前一结点的首地址