简介-链表(LinkedList)是以节点的形式存储的,是一种链式存储-节点不一定是连续存储-链表分为有前导节点的链表和无前导节点的链表链表包括一-单向链表、双向链表和单向环链表。单向链表的每个节点包含数据字段和下一个字段:指向下一个节点。下面用一个简单的例子来说明单向链表的增删改查。比如我们用一个简单的水浒英雄排名管理实例,来实现一个单向链表。首先创建一个类来存放各个节点存储的英雄信息:no=$no;$this->名字=$名字;$this->昵称=$昵称;}//重写__toString以便于打印publicfunction__toString(){return'Number:'.$this->no.'名称:'.$this->name.'昵称:'.$this->nickName."\n";}}创建一个管理英雄的类/***水浒英雄列表*ClassSingleLinkedList*/classSingleLinkedList{public$header;//publicfunction__construct(){//先初始化一个头节点,头节点不动,不存储具体数据$this->header=newHeroNode(0,'','');}}接下来我们将英雄添加到链表中,直接将英雄插入到链表的末尾。/***水浒英雄链表*ClassSingleLinkedList*/classSingleLinkedList{.../***在链表末尾插入*@param$hero*/publicfunctionadd($hero){//创建指向头节点的临时变量$temp=$this->标题;//遍历链表找到链表的尾部while(true){//如果next字段为空,找到尾部并退出循环if($temp->next==null){break;}$temp=$temp->下一个;}//将英雄添加到链表的末尾$temp->next=$hero;}}还有一种添加方式,就是按照英雄的数量从小到大添加/***水浒英雄列表*ClassSingleLinkedList*/classSingleLinkedList{.../***根据插入从小到大的数字*@param$hero*/privatefunctionaddByOrder($hero){$temp=$this->header;$标志=假;while(true){if($temp->next==null){中断;}//如果下一个节点的个数大于插入英雄的个数,则将其插入到下一个节点的前面if($temp->next->no>$hero->no){break;}if($temp->next->no==$hero->no){$标志=真;休息;}$temp=$temp->下一个;}if($flag==true){echo'number'.$hero->no.'已经存在,无法插入';}else{$hero->next=$temp->next;$temp->next=$hero;}}}修改节点也是通过遍历链表,修改要修改的数/***修改节点*@param$hero*/publicfunctionupdate($hero){$temp=$this->标头;$标志=假;while(true){if($temp->next==null){中断;}if($temp->next->no==$hero->no){$flag=true;休息;}$temp=$temp->下一个;}if($flag==true){$temp->next->name=$hero->name;$temp->next->nickName=$hero->nickName;}else{echo'编号为'.$hero->no.'的英雄未找到且无法修改';}}删除节点通过Traverse找到数,然后将temp的next字段指向temp的nextnext字段,实现删除/***deletenode*@param$no*/publicfunctiondel($no){$temp=$this->header;$标志=假;while(true){if($temp->next===null){中断;}if($temp->next->no==$no){$flag=true;休息;}$temp=$temp->下一个;}if($flag==true){$temp->next=$temp->next->next;}else{echo"没有找到编号为".$no."的英雄,删除失败";}}添加打印链表的函数/***打印链表*/publicfunctionlists(){$temp=$this->header;while(true){if($temp->next==null){中断;}$temp=$temp->下一个;回声$温度;}}扩展一个反向链表的功能,增加一个新的链表,遍历原链表,每遍历一个结点就将结点插入新链表的头部,最后指向next的字段原链表到新链表的下一个字段/***链表反转*/publicfunctionreverse(){if($this->header->next==null||$this->header->next->next==null){返回;}$reverseHeader=newHeroNode('','','','');$cur=$this->header->next;$下一个=空;while($cur!=null){$next=$cur->next;$cur->next=$reverseHeader->next;$reverseHeader->next=$cur;$cur=$next;$this->header->next=$reverseHeader->next;}
