• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

PHP如何实现双链表删除与插入节点的方法

php 搞代码 3年前 (2022-01-22) 30次浏览 已收录 0个评论

这篇文章主要介绍了PHP实现双链表删除与插入节点的方法,结合实例形式分析了PHP双链表的定义与节点操作相关实现技巧,需要的朋友可以参考下

具体如下:

概述:

双向链表也叫双链表,是链表的一种,它的每个数据结点中都有两个指针,分别指向直接后继和直接前驱。所以,从双向链表中的任意一个结点开始,都可以很方便地访问它的前驱结点和后继结点。一般我们都构造双向循环链表。

实现代码:

<?php class node{  public $prev;  public $next;  public $data;  public function __construct($data,$prev=null,$next=null){    $this->data=$data;    $this->prev=$prev;    $this->next=$next;  }}class doubleLinkList{  private $head;  public function __construct()  {    $this->head=new node("head",null,null);  }  //插入节点  public function insertLink($data){    $p=new node($data,null,null);    $q=$this->head->next;    $r=$this->head;    while($q){      if($q->data>$data){        $q->prev->next=$p;        $p->prev=$q->prev;        $p->next=$q;        $q->prev=$p;      }else{      $r=$q;$q=$q->next;      }    }    if($q==null){      $r->next=$p;      $p->prev=$r;    }  }  //从头输出节点  public function printFromFront(){    $p=$this->head->next;    $string="";    while($p){    $string.=$string?",":"";    $string.=$p->data;    $p=$p->next;    }    echo $string."<br>";  }  //从尾输出节点  public function printFromEnd(){    $p=$this->head->next;    $r=$this->head;    while($p){    $r=$p;$p=$p->next;    }    $string="";    while($r){      $string.=$string?",":"&q<strong>*本文来源gaodai#ma#com搞@代~码^网+</strong><strong>搞代gaodaima码</strong>uot;;      $string.=$r->data;      $r=$r->prev;    }    echo $string."<br>";  }  public function delLink($data){    $p=$this->head->next;    if(!$p)    return;    while($p){      if($p->data==$data)      {        $p->next->prev=$p->prev;        $p->prev->next=$p->next;        unset($p);        return;      }      else{        $p=$p->next;      }    }    if($p==null)    echo "没有值为{$data}的节点";  }}$link=new doubleLinkList();$link->insertLink(1);$link->insertLink(2);$link->insertLink(3);$link->insertLink(4);$link->insertLink(5);$link->delLink(3);$link->printFromFront();$link->printFromEnd();$link->delLink(6);

运行结果:

1,2,4,55,4,2,1,head没有值为6的节点

相关推荐:

JS操作DOM插入节点

JS怎样实现DOM插入节点

jQuery插入节点insertAfter和移动节点insertBefore用法示例

以上就是PHP如何实现双链表删除与插入节点的方法的详细内容,更多请关注搞代码gaodaima其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:PHP如何实现双链表删除与插入节点的方法

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址