当前位置: 首页 > 后端技术 > PHP

基于实际PHP数据结构的单向链表

时间:2023-03-29 15:29:48 PHP

什么是链表?链表由一个个对象作为节点组成,每个节点都有一个指向下一个节点的指针,最后一个节点的指针字段指向NULL。每个节点都可以存储任何数据类型。常用操作我们对单向链表的常用操作如下:类ListNode{私有$data;私人$下一个;公共函数__construct(string$data){$this->data=$data;}公共函数__get($var){返回$this->$var;}公共函数__set($var,$val){return$this->$var=$val;}}让我们再看看链表类。首先,我们需要两个私有属性,即头节点和长度。类LinkedList{私有$head;private$length;}长话短说,看看如何实现第一个也是常用的插入,这是一个平均时间复杂度为O(n)的操作。/***插入一个节点*@paramstring|null$data*@returnbool*复杂度O(n)*/publicfunctioninsert(string$data=null){$newNode=newListNode($data);如果($this->head===null){$this->head=&$newNode;}else{$currentNode=$this->head;while($currentNode->next!==null){$currentNode=$currentNode->next;}$currentNode->next=$newNode;}$this->length++;returntrue;}再看search,也是一个平均时间复杂度为O(n)的操作。/***搜索一个节点*@paramstring$data*@returnbool|ListNode*复杂度O(n)*/publicfunctionsearch(string$data){if($this->length>0){$currentNode=$这个->头;while($currentNode!==null){if($currentNode->data===$data){返回$currentNode;}$currentNode=$currentNode->next;}}returnfalse;}反向单链表publicfunctionreverse(){if($this->head!==null){if($this->head->next!==null){$reveredList=null;$下一个=空;$currentNode=$this->head;while($currentNode!==null){$next=$currentNode->next;$currentNode->next=$reveredList;$reveredList=$currentNode;$currentNode=$next;}$this->head=$reveredList;单链表其他操作的详细实现可以在这里找到。单向链表是链表的基本部分,是一种链式访问数据结构。属于链表结构的还有双链表、循环链表和多链表。专题系列PHP基本数据结构专题系列目录地址:https://github.com/...主要用PHP语法总结基本数据结构和算法。还有我们日常PHP开发中容易忽略的基础知识和现代PHP开发中规范、部署、优化的一些实用建议,以及对Javascript语言特性的深入研究。