PHP單鏈表的實現(xiàn)代碼
單鏈表是一種鏈式存取的數(shù)據(jù)結(jié)構(gòu),用一組地址任意的存儲單元存放線性表中的數(shù)據(jù)元素。
單鏈表簡介
鏈表中的數(shù)據(jù)是以結(jié)點來表示的,每個結(jié)點的構(gòu)成:元素(數(shù)據(jù)元素的映象) + 指針(指示后繼元素存儲位置),元素就是存儲數(shù)據(jù)的存儲單元,指針就是連接每個結(jié)點的地址數(shù)據(jù)。
關鍵代碼如下所示:
<?php
/**
* 單鏈表
*/
class Demo
{
private $id;
public $name;
public $next;
public function __construct ($id = '', $name = '')
{
$this->id = $id;
$this->name = $name;
}
static public function show ($head)
{
$cur = $head;
while ($cur->next) {
echo $cur->next->id,'###',$cur->next->name,'<br />';
$cur = $cur->next;
}
echo '<hr />';
}
//尾插法
static public function push ($head, $node)
{
$cur = $head;
while (NULL != $cur->next) {
$cur = $cur->next;
}
$cur->next = $node;
return $head;
}
static public function insert($head, $node)
{
$cur = $head;
while (NULL != $cur->next) {
if ($cur->next->id > $node->id) {
break;
}
$cur = $cur->next;
}
$node->next = $cur->next;
$cur->next = $node;
return $head;
}
static public function edit($head, $node)
{
$cur = $head;
while (NULL != $cur->next) {
if ($cur->next->id == $node->id) {
break;
}
$cur = $cur->next;
}
$cur->next->name = $node->name;
return $head;
}
static public function pop ($head, $node)
{
$cur = $head;
while (NULL != $cur->next) {
if ($cur->next == $node) {
break;
}
$cur = $cur->next;
}
$cur->next = $node->next;
return $head;
}
}
$team = new Demo();
$node1 = new Demo(1, '唐三藏');
Demo::push($team, $node1);
$node1->name = '唐僧';
Demo::show($team);
// Demo::show($team);
$node2 = new Demo(2, '孫悟空');
Demo::insert($team, $node2);
// Demo::show($team);
$node3 = new Demo(5, '白龍馬');
Demo::push($team, $node3);
// Demo::show($team);
$node4 = new Demo(3, '豬八戒');
Demo::insert($team, $node4);
// Demo::show($team);
$node5 = new Demo(4, '沙和尚');
Demo::insert($team, $node5);
// Demo::show($team);
$node4->name = '豬悟能';//php對象傳引用,所以Demo::edit沒有必要
// unset($node4);
// $node4 = new Demo(3, '豬悟能');
// Demo::edit($team, $node4);
Demo::pop($team, $node1);
Demo::show($team);
以上所述是小編給大家介紹的PHP單鏈表的實現(xiàn)代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關文章
使用pthreads實現(xiàn)真正的PHP多線程(需PHP5.3以上版本)
PHP 5.3 以上版本,使用pthreads PHP擴展,可以使PHP真正地支持多線程。多線程在處理重復性的循環(huán)任務,能夠大大縮短程序執(zhí)行時間2014-05-05
Laravel+Intervention實現(xiàn)上傳圖片功能示例
這篇文章主要介紹了Laravel+Intervention實現(xiàn)上傳圖片功能,結(jié)合實例形式分析了Intervention的安裝及圖片上傳功能的相關設置、使用與注意事項,需要的朋友可以參考下2019-07-07
laravel實現(xiàn)按月或天或小時統(tǒng)計mysql數(shù)據(jù)的方法
今天小編就為大家分享一篇laravel實現(xiàn)按月或天或小時統(tǒng)計mysql數(shù)據(jù)的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-10-10
PHP將URL轉(zhuǎn)換成短網(wǎng)址的算法分享
短網(wǎng)址(Short URL)顧名思義就是在形式上比較短的網(wǎng)址。在Web 2.0的今天,不得不說這是一個潮流。目前已經(jīng)有許多類似服務,借助短網(wǎng)址您可以用簡短的網(wǎng)址替代原來冗長的網(wǎng)址,讓使用者可以更容易的分享鏈接,下面來看看如何用PHP實現(xiàn)這個功能,有需要的朋友們可以參考。2016-09-09

