PHP小教程之實現(xiàn)雙向鏈表
更新時間:2014年06月12日 09:06:29 投稿:hebedich
雙向鏈表也叫雙鏈表,是鏈表的一種,它的每個數(shù)據(jù)結點中都有兩個指針,分別指向直接后繼和直接前驅。所以,從雙向鏈表中的任意一個結點開始,都可以很方便地訪問它的前驅結點和后繼結點。一般我們都構造雙向循環(huán)鏈表。
看了很久數(shù)據(jù)結構但是沒有怎么用過,在網(wǎng)上看到了關于PHP的數(shù)據(jù)結構,學習了一下,與大家一起分享一下。上一次分享了《PHP小教程之實現(xiàn)鏈表》,這次來補充說一下雙向鏈表。
復制代碼 代碼如下:
<?php
class Hero
{
public $pre=null;
public $no;
public $name;
public $next=null;
public function __construct($no='',$name='')
{
$this->no=$no;
$this->name=$name;
}
static public function addHero($head,$hero)
{
$cur = $head;
$isExist=false;
//判斷目前這個鏈表是否為空
if($cur->next==null)
{
$cur->next=$hero;
$hero->pre=$cur;
}
else
{
//如果不是空節(jié)點,則安排名來添加
//找到添加的位置
while($cur->next!=null)
{
if($cur->next->no > $hero->no)
{
break;
}
else if($cur->next->no == $hero->no)
{
$isExist=true;
echo "<br>不能添加相同的編號";
}
$cur=$cur->next;
}
if(!$isExist)
{
if($cur->next!=null)
{
$hero->next=$cur->next;
}
$hero->pre=$cur;
if($cur->next!=null)
{
$hero->next->pre=$hero;
}
$cur->next=$hero;
}
}
}
//遍歷
static public function showHero($head)
{
$cur=$head;
while($cur->next!=null)
{
echo "<br>編號:".$cur->next->no."名字:".$cur->next->name;
$cur=$cur->next;
}
}
static public function delHero($head,$herono)
{
$cur=$head;
$isFind=false;
while($cur!=null)
{
if($cur->no==$herono)
{
$isFind=true;
break;
}
//繼續(xù)找
$cur=$cur->next;
}
if($isFind)
{
if($cur->next!=null)
{
$cur->next_pre=$cur->pre;
}
$cur->pre->next=$cur->next;
}
else
{
echo "<br>沒有找到目標";
}
}
}
$head = new Hero();
$hero1 = new Hero(1,'1111');
$hero3 = new Hero(3,'3333');
$hero2 = new Hero(2,'2222');
Hero::addHero($head,$hero1);
Hero::addHero($head,$hero3);
Hero::addHero($head,$hero2);
Hero::showHero($head);
Hero::delHero($head,2);
Hero::showHero($head);
?>
相關文章
Codeigniter+PHPExcel實現(xiàn)導出數(shù)據(jù)到Excel文件
PHPExcel是用來操作OfficeExcel文檔的一個PHP類庫,Codeigniter是一個功能強大的PHP框架。二者結合就能起到非常棒的效果,需要的朋友可以參考下2014-06-06
php使用strtotime和date函數(shù)判斷日期是否有效代碼分享
php使用strtotime和date函數(shù)進行檢驗判斷日期是否有效代碼分享,大家參考使用吧2013-12-12
PHP使用Redis實現(xiàn)Session共享的實現(xiàn)示例
這篇文章主要介紹了PHP使用Redis實現(xiàn)Session共享的實現(xiàn)示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-05-05

