martingold/linked-list

提供排序链表的库

0.1.0 2023-11-03 10:29 UTC

This package is auto-updated.

Last update: 2024-09-06 12:04:16 UTC


README

提供标准排序链表实现的库。严格版本提供了对列表中类型的检查,使其适合非类型检查的代码库。

安装

您可以使用Composer安装此库

composer require martingold/linked-list

用法

require 'vendor/autoload.php';

use MartinGold\LinkedList\SortedLinkedList;

$list = new SortedLinkedList();

$list->insert(1);
$list->insert(3);
$list->insert(7);

var_dump($list->pop());

支持以下列表操作:insertgetcontainsshiftpop

如果需要在非类型安全的代码库中进行运行时检查,请考虑使用StrictSortedLinkedList实现,它将在运行时执行类型检查。

自定义排序实现

默认的排序实现使用的是飞船运算符。如果您需要根据需求对值进行排序,可以使用自己的Comparator实现。

use MartinGold\LinkedList\Comparator\Comparator;
use MartinGold\LinkedList\SortedLinkedList;

class Product
{
    public function __construct(
        public readonly float $quantity, 
    ){
        //
    }
}

/**
 * @implements Comparator<Product>
 */
class ProductComparator implements Comparator
{
    /**
     * Returns 1 when $a value is greater than $b.
     * Returns 0 when $a value is same as $b value.
     * Returns -1 when $a value is lesser than $b.
     */
    public function compare(Product $a, Product $b): int
    {
        return $a->quantity <=> $b->quantity;
    }
}

$productList = new SortedLinkedList(new ProductComparator());
$productList->insert(new Product(20));
$productList->insert(new Product(31));
$productList->insert(new Product(12));

foreach ($productList as $product) {
    echo $product->quantity;
}

// 12
// 20
// 31

要求

php >= 8.2

无需其他依赖。

贡献

根据需要修改库,然后运行

composer qa

请在提交拉取请求之前确保此脚本成功执行。该脚本执行了符合编码标准的检查和静态分析检查。

如果遇到代码风格错误,可以通过运行自动修复

composer csf

许可证

此库为开源软件,可在MIT许可证下使用。