实例讲述PHP实现双链表删除与插入节点的方法

2018-06-22 00:59:07来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

本文实例讲述了PHP实现双链表删除与插入节点的方法。分享给大家供大家参考,具体如下:

概述:

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

实现代码:

php.html="" tags="">
php;">
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."
";
  }
  //从尾输出节点
  public function printFromEnd(){
    $p=$this->head->next;
    $r=$this->head;
    while($p){
    $r=$p;$p=$p->next;
    }
    $string="";
    while($r){
      $string.=$string?",":"";
      $string.=$r->data;
      $r=$r->prev;
    }
    echo $string."
";
  }
  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);

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:thinkphp5使用bootstrapvalidator进行异步验证邮箱的示例

下一篇:用php实现网页常见的文件上传功能