php实现一个单向链表

class Singlelist{
    
    private $head;
    
    private $size;
    
    public function __construct(){
        $this->head = null;
        $this->size = 0;
    }
    
    public function get($index){
        if ($index>=$this->size || $index<0) return false;
        $node = $this->head;
        for ($i=0;$i<$index;$i++){
            $node = $node->next;
        }
        return $node;
    }
    
    public function insert($data, $index=''){
        $index = $index ? $index : $this->size;
        if ($index>$this->size || $index<0) return false;
        $new_node = new Node($data);
        if ($index==0) {
            $this->head = $new_node;
        }elseif ($index==$this->size){
            $this->get($this->size-1)->next = &$new_node;
        }else{
            $next_node = $this->get($index);
            $this->get($index-1)->next = &$new_node;            
            $new_node->next = &$next_node;
        }
        $this->size++;
        return true;
    }
    
    public function update($data, $index){
        if ($index>=$this->size || $index<0) return false;
        $this->get($index-1)->data = $data;
        return true;
    }
    
    public function delete($index){
        if ($index>=$this->size || $index<0) return false;
        if ($index==0){
            $this->head = $this->get(1);
        }elseif ($index==$this->size-1){
            $this->get($index-1)->next = null;
        }else{
            //$this->get($index-1)->next = &$this->get($index+1);
            $per_node = $this->get($index-1);
            $next_node = $per_node->next->next;
            $per_node->next = &$next_node;
        }
        $this->size--;
        return true;
    }
    
}

class Node{
    
    public $data;
    
    public $next;
    
    public function __construct($data){
        $this->data = $data;
    }
    
}


$list = new Singlelist();
$list->insert(2);
$list->insert(5);
$list->insert(6);
$list->insert(7);
$list->insert(8);
$list->insert(9);
var_dump($list->get(2)->data);

结果输出6

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值