Logo

Lista

这是我的链表。虽然有很多类似的,但这个是我的,用 Swift 写的。

目前用于

详细文档可以在这里找到

概述

我发现自己在各种场合经常需要链表结构,要么必须自己编写,要么导入一些庞大(且通常很出色)的包含多种算法和存储类型的包。我只是想要一个小型且快速的链表,没有依赖项,所以我最终编写了这个,并且由于我最终在多个地方使用了它,因此我将其放在这里供其他人使用/复制/调整/改进。

用法

Lista 是一个泛型 Swift Collection,实现为简单的单链表,并符合 Codable 协议,用于序列化和反序列化。它也是 Sendable 并且是线程安全的。它具有预期的性能特征。我发现它在实现堆栈和 FIFO 链时最有用,以及在需要将未知(但通常很大)数量的项目串行追加到列表时使用。请参阅下面的 API 部分,了解提供的所有便捷方法。

let list = Lista<Int>()

list.append(1) // 1
list.append(contentsOf: [2, 3, 4]) // 1,2,3,4
print(list.last!) // 4

let popped = list.pop() // 2,3,4
print(popped!) // 1
print(list.first!) // 2

list.push(1) // 1,2,3,4
list.push(0) // 0,1,2,3,4
print(list.first!) // 0
print(list.count) // 5

let doubled = list.map { $0 * 2 }
print(doubled) // 0,2,4,6,8

API

// Create, count items, get first or last items, if they exist
init(value: Value? = nil)
var count: Int
var first: Value?
var last: Value?

// Push and pop from the start of the list
func push(_ value: Value)
func pop() -> Value?

// Adding an element to the end of the list
func append(_ value: Value)

// Link another Lista to the end of this. Very fast.
func append(contentsOf collection: Lista<Value>)

// Append each element to the current list. Linear time.
func append<S: Sequence>(from sequence: S) where S.Iterator.Element == Value

// Removing elements. The first method is fast, the others require linear time.
func removeAll()
func remove(first removeCheck: (Value) -> Bool) -> Bool
func removeAll(where removeCheck: (Value) -> Bool)

以下方法允许随机访问,但是,顾名思义,它们很慢。如果您发现自己经常使用它们,那么链表可能不是正确的解决方案 :)

// Item at `index`
func slowItem(at index: Int) -> Value?

// Insert item at `index`, returns if it was inserted
func slowInsert(_ value: Value, at index: Int) -> Bool

// Remove item at `index`, returns the item that was removed
func slowRemove(at index: Int) -> Value?

// Remove item at the end - shorthand for `list.slowRemove(at: list.count - 1)`
func slowDropLast() -> Value?

如果 Value 类型是 Codable,那么 Lista 也将有条件地符合该协议,因此可以轻松地进行序列化和反序列化。

extension Lista: Codable where Value: Codable

如果 Value 类型是一个对象,则一种特定于性能的方法允许通过内部使用引用比较而不是相等运算符来检测项目。

func removeInstance(of item: Value) -> Bool

许可

版权所有 (c) 2023 Paul Tsochantaris。根据 MIT 许可证获得许可,详细信息请参阅 LICENSE。