浅谈PHP数据结构之单链表

来源:互联网 发布:淘宝集运澳洲怎么收费 编辑:程序博客网 时间:2024/05/21 22:23

什么是链表?(根据百度词条查询而得)

链表是一种物理存储单元上非连续、非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的。链表由一系列结点(链表中每一个元素称为结点)组成,结点可以在运行时动态生成。每个结点包括两个部分:一个是存储数据元素的数据域,另一个是存储下一个结点地址的指针域。

经过查询资料和观摩了网站不同版本的链表后,小弟自己尝试着写了一个PHP版本的单链表,希望对大家理解链表有所帮助。

<?php
//定义结点
class Node{
    public $id;//结点ID
    public $data;//结点数据
    public $next;//指向下一结点
    public function __construct($id,$data){
        $this->id=$id;
        $this->data=$data;
        $this->next=NULL;
    }
}
class Linklist{
    private $head;//定义头结点
    public function __construct($id=0,$data=NULL){
        $this->head=new Node($id,$data);
    }
    //插入结点
    public function addNode($node){
        $head=$this->head;
        //插入之前检查ID是否冲突
        if($this->getNode($node->id)!=false){
            echo "您要插入的ID为".$node->id."数据为".$node->data."的结点已经存在该ID,请修改ID后重试<br>";
            return false;
        }
        while($head->next!=NULL){
            if($head->next->id >= $node->id){
                break;
            }
            $head=$head->next;
        }
        $node->next=$head->next;
        $head->next=$node;

    }

    //删除结点
    public function delNode($id){
        $head=$this->head;
        $temp=false;
        //注意,删除操作需要找到需要删除的前一个结点
        while($head->next != NULL){
            if($head->next->id==$id){
                $temp=true;
                break;
            }
            $head=$head->next;
        }
        if($temp==true){
            if($head->next->next==null){
                $head->next=NULL;
            }
            else
                $head->next=$head->next->next;
            
        return true;
    }
    else {
        echo '未找到id为'.$id.'的结点<br>';
    }
    }

    //获取链表
    public  function getList(){
        $head=$this->head;
        if($head->next==NULL){
            echo '该链表为空';
        }
        while($head->next !=NULL){
            if($head->id != 0)
            echo 'ID为'.$head->id.'的结点中的数据为'.$head->data.'<br/>';
            $head=$head->next;
        }
            echo 'ID为'.$head->id.'的结点中的数据为'.$head->data;
    }

    //获取结点
    public function getNode($id){
        $head=$this->head;
        while($head !=NULL){
            if($head->id==$id)
                return $head->data;
            $head=$head->next;
        }
        return false;
    }

    //获取长度
    public function getLength(){
        $head=$this->head;
        $num=0;
        while($head->next !=NULL){
            $num++;
            $head=$head->next;
        }
        return $num;
    }
}
$a=new Linklist;
$a->addNode(new Node(1,"Hello Word"));
$a->addNode(new Node(2,3));
$a->addNode(new Node(2,11123));
$a->addNode(new Node(3,11123));
$a->getList();
$b=$a->getNode(3);
$c=$a->getLength();
var_dump($b);
var_dump($c);
?>

最后为测试代码,下面是测试结果:

小弟初学,哪里不对的希望大家可以包容下,给点建议。

1 0