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结合Ueditor并修改图片上传路径

PHP结合Ueditor并修改图片上传路径

前言 在使用UEditor编辑器时,一般我们都是需要修改默认的图片上传路径的,下面是我整理好的修改位置和方法供大家参考。 操作 Ueditor PHP版本本身自带了一套上传程序,我们...

php 短链接算法收集与分析

短链接就不说了,大家已经都清楚了,如下所示就是短链接: 新浪微博 http://t.cn/SVpONM 腾讯微博 http://url.cn/302yor Yun.io http://d...

php获取url字符串截取路径的文件名和扩展名的函数

php获取文件名复制代码 代码如下: function retrieve($url) { preg_match('/\/([^\/]+\.[a-z]+)[^\/]*$/',$url,$m...

php define的第二个参数使用方法

看手册说define定义的常量只允许:仅允许标量和 null。标量的类型是 integer, float,string 或者 boolean。 也能够定义常量值的类型为 resource...

php中session与cookie的比较

本文较为详细的比较了php中session与cookie区别。分享给大家供大家参考。具体分析如下: 1、存放的位置 cookie保存在客户端,session保存在服务器端的文件系统/数据...