PHP实现双链表删除与插入节点的方法示例
author:一佰互联 2019-04-25   click:154

本文实例讲述了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?",":"";      $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的节点

更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP数据结构与算法教程》、《php程序设计算法总结》、《php字符串(string)用法总结》、《PHP数组(Array)操作技巧大全》、《PHP常用遍历算法与技巧总结》及《PHP数学运算技巧总结》

希望本文所述对大家PHP程序设计有所帮助。