PHP实现线性表的顺序存储结构

本文详细介绍了线性表的基本概念、初始化、销毁、判断空表、获取元素个数、定位元素、插入元素、删除元素等核心操作及其实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class SqList
{
    public $elem;
    public $length;
    public $size;
}

class Linear
{
    const LIST_INIT_SIZE = 10;
    const LIST_INCREMENT = 5;
    private $list = null;

    /**
     * 构造一个空的线性表
     */
    public function initList()
    {
        $this->list = new SqList();
        $this->list->elem = array();
        $this->list->length = 0;
        $this->list->size = self::LIST_INIT_SIZE;
        return true;
    }

    /**
     * 销毁线性表
     */
    public function destoryList()
    {
        if (is_object($this->list)) {
            $this->list = null;
        }
    }

    /**
     * 是否为空表
     */
    public function listEmpty()
    {
        if (is_object($this->list)) {
            return $this->list->length == 0 ? true : false;
        }
    }

    /**
     * 返回元素个数
     */
    public function listLength()
    {
        if (is_object($this->list)) {
            return $this->list->length;
        }
    }

    /**
     * 获取指定位置的元素
     */
    public function getElem($i)
    {
        if ($i < 1 || $i > $this->list->length + 1) {
            return false;
        }
        return $this->list->elem[$i-1];
    }

    /**
     * 在指定位置插入元素
     */
    public function listInsert($i, $e)
    {
        if ($i < 1 || $i > $this->list->length + 1) {
            return false;
        }
        if ($this->list->length >= $this->list->size) {
            $this->list->size += self::LIST_INCREMENT;
        }
        for ($j = $this->list->length; $j >= $i; $j--) {
            $this->list->elem[$j] = $this->list->elem[$j-1];
        }
        $this->list->elem[$i-1] = $e;
        $this->list->length++;
    }

    /**
     * 删除指定位置数据元素
     */
    public function listDelete($i)
    {
        if ($i < 1 || $i > $this->list->length) {
            return false;
        }
        $data = $this->list->elem[$i-1];
        for ($j = $i -1; $j < $this->list->length -1; $j++) {
            $this->list->elem[$j] = $this->list->elem[$j+1];
        }
        unset($this->list->elem[$this->list->length-1]);
        $this->list->length--;
        return $data;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值