php 实现单链表的增删改查

<?php

class Node
{
    public $value;
    public $next;

    public function __construct($value = null)
    {
        $this->value = $value;
        $this->next = null;
    }
}

class SingleLinkList
{
    public $head;

    public function __construct()
    {
        $this->head = new Node();
    }


    public function count()
    {
        $current = $this->head;
        $i = 0;
        while (!is_null($current->next)) {
            $i++;
            $current = $current->next;
        }
        return $i;
    }

    public function add($value)
    {
        $current = $this->head;
        while (!is_null($current->next)) {
            $current = $current->next;
        }

        $newNode = new Node($value);
        $current->next = $newNode;
    }

    public function insert($no, $data)
    {
        if ($no > $this->count())
            return false;
        $current = $this->head;
        $newNode = new Node($data);

        for ($i = 0; $i < $no; $i++) {
            $current = $current->next;
        }

        $newNode->next = $current->next;
        $current->next = $newNode;
        return true;
    }

    public function update($no, $data)
    {
        if ($no > $this->count())
            return false;
        $current = $this->head;
        for ($i = 0; $i < $no; $i++) {
            $current = $current->next;
        }
        $current->value = $data;
        return true;

    }

    public function del($no)
    {
        if ($no > $this->count())
            return false;
        $current = $this->head;

        for ($i = 0; $i < $no - 1; $i++) {
            $current = $current->next;
        }
        $current->next = $current->next->next;
        return true;
    }

    public function show()
    {
        $current = $this->head;
        while (!is_null($current->next)) {
            $current = $current->next;
            echo $current->value . " ";
        }
    }

}

$a = new SingleLinkList();

$a->add('a');
$a->add('b');
$a->add('c');
$a->add('d');
$a->add('e');
$a->add('f');
$a->add('g');

var_dump($a->insert(1, "hello"));
var_dump($a->del(2));
var_dump($a->update(2, 'world'));
$a->show();
var_dump($a->head);


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值