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

yipeiwu_com6年前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?",":"";
      $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,5
5,4,2,1,head
没有值为6的节点

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

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

相关文章

php 按指定元素值去除数组元素的实现方法

按指定元素值去除数组元素 复制代码 代码如下: <?php //去除值为"Cat"的元素 $a=array("a"=>"Dog","b"=>"Cat","c"=>...

php 备份数据库代码(生成word,excel,json,xml,sql)

单表备份代码:复制代码 代码如下:<?php    class Db    {    &n...

php_xmlhttp 乱码问题解决方法

resin在新版本中竟开始支持php了,偶感觉比较好玩,也是懒得在自己机器上再配置一组apache_php_mysql之流,毕竟以java为主做事情的嘛。于是将自己的一个php站点直接放...

PHP读取目录树的实现方法分析

PHP读取目录树的实现方法分析

本文实例讲述了PHP读取目录树的实现方法。分享给大家供大家参考,具体如下: 前一阵时间面试XX公司笔试题中竟然有这样一道题: 使用PHP列出目录树! 当时一看就懵逼了!基本的思路还是有的...

php向js函数传参的几种方法

<?php echo "<script>test('$_POST[userid]');</script> "; ?> 在上面的...