当前位置:首页 > PHP教程 > php应用 > 列表

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

发布:smiling 来源: PHP粉丝网  添加日期:2021-08-19 10:12:02 浏览: 评论:0 

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

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

概述:

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

实现代码:

  1. <?php  
  2. class node{ 
  3.   public $prev; 
  4.   public $next; 
  5.   public $data; 
  6.   public function __construct($data,$prev=null,$next=null){ 
  7.     $this->data=$data; 
  8.     $this->prev=$prev; 
  9.     $this->next=$next; 
  10.   } 
  11. } 
  12. class doubleLinkList{ 
  13.   private $head; 
  14.   public function __construct() 
  15.   { 
  16.     $this->head=new node("head",null,null); 
  17.   } 
  18.   //插入节点 
  19.   public function insertLink($data){ 
  20.     $p=new node($data,null,null); 
  21.     $q=$this->head->next; 
  22.     $r=$this->head; 
  23.     while($q){ 
  24.       if($q->data>$data){ 
  25.         $q->prev->next=$p; 
  26.         $p->prev=$q->prev; 
  27.         $p->next=$q; 
  28.         $q->prev=$p; 
  29.       }else{ 
  30.       $r=$q;$q=$q->next; 
  31.       } 
  32.     } 
  33.     if($q==null){ 
  34.       $r->next=$p; 
  35.       $p->prev=$r; 
  36.     } 
  37.   } 
  38.   //从头输出节点 
  39.   public function printFromFront(){ 
  40.     $p=$this->head->next; 
  41.     $string=""; 
  42.     while($p){ 
  43.     $string.=$string?",":""; 
  44.     $string.=$p->data; 
  45.     $p=$p->next; 
  46.     } 
  47.     echo $string."<br>"; 
  48.   } 
  49.   //从尾输出节点 
  50.   public function printFromEnd(){ 
  51.     $p=$this->head->next; 
  52.     $r=$this->head; 
  53.     while($p){ 
  54.     $r=$p;$p=$p->next; 
  55.     } 
  56.     $string=""; 
  57.     while($r){ 
  58.       $string.=$string?",":""; 
  59.       $string.=$r->data; 
  60.       $r=$r->prev; 
  61.     } 
  62.     echo $string."<br>"; 
  63.   } 
  64.   public function delLink($data){ 
  65.     $p=$this->head->next; 
  66.     if(!$p) 
  67.     return; 
  68.     while($p){ 
  69.       if($p->data==$data) 
  70.       { 
  71.         $p->next->prev=$p->prev; 
  72.         $p->prev->next=$p->next; 
  73.         unset($p); 
  74.         return; 
  75.       } 
  76.       else{ 
  77.         $p=$p->next; 
  78.       } 
  79.     } 
  80.     if($p==null) 
  81.     echo "没有值为{$data}的节点"; 
  82.   } 
  83. } 
  84. $link=new doubleLinkList(); 
  85. $link->insertLink(1); 
  86. $link->insertLink(2); 
  87. $link->insertLink(3); 
  88. $link->insertLink(4); 
  89. $link->insertLink(5); 
  90. $link->delLink(3); 
  91. $link->printFromFront(); 
  92. $link->printFromEnd(); 
  93. $link->delLink(6); 

运行结果:

1,2,4,5

5,4,2,1,head

没有值为6的节点

Tags: PHP双链表删除 PHP插入节点

分享到: