mirror of
https://github.com/krahets/hello-algo.git
synced 2026-07-09 14:06:06 +00:00
Add build script for Swift.
This commit is contained in:
@@ -956,99 +956,7 @@ comments: true
|
||||
=== "Swift"
|
||||
|
||||
```swift title="my_list.swift"
|
||||
/* 列表类简易实现 */
|
||||
class MyList {
|
||||
private var nums: [Int] // 数组(存储列表元素)
|
||||
private var _capacity = 10 // 列表容量
|
||||
private var _size = 0 // 列表长度(即当前元素数量)
|
||||
private let extendRatio = 2 // 每次列表扩容的倍数
|
||||
|
||||
/* 构造函数 */
|
||||
init() {
|
||||
nums = Array(repeating: 0, count: _capacity)
|
||||
}
|
||||
|
||||
/* 获取列表长度(即当前元素数量)*/
|
||||
func size() -> Int {
|
||||
_size
|
||||
}
|
||||
|
||||
/* 获取列表容量 */
|
||||
func capacity() -> Int {
|
||||
_capacity
|
||||
}
|
||||
|
||||
/* 访问元素 */
|
||||
func get(index: Int) -> Int {
|
||||
// 索引如果越界则抛出错误,下同
|
||||
if index < 0 || index >= _size {
|
||||
fatalError("索引越界")
|
||||
}
|
||||
return nums[index]
|
||||
}
|
||||
|
||||
/* 更新元素 */
|
||||
func set(index: Int, num: Int) {
|
||||
if index < 0 || index >= _size {
|
||||
fatalError("索引越界")
|
||||
}
|
||||
nums[index] = num
|
||||
}
|
||||
|
||||
/* 尾部添加元素 */
|
||||
func add(num: Int) {
|
||||
// 元素数量超出容量时,触发扩容机制
|
||||
if _size == _capacity {
|
||||
extendCapacity()
|
||||
}
|
||||
nums[_size] = num
|
||||
// 更新元素数量
|
||||
_size += 1
|
||||
}
|
||||
|
||||
/* 中间插入元素 */
|
||||
func insert(index: Int, num: Int) {
|
||||
if index < 0 || index >= _size {
|
||||
fatalError("索引越界")
|
||||
}
|
||||
// 元素数量超出容量时,触发扩容机制
|
||||
if _size == _capacity {
|
||||
extendCapacity()
|
||||
}
|
||||
// 将索引 index 以及之后的元素都向后移动一位
|
||||
for j in sequence(first: _size - 1, next: { $0 >= index + 1 ? $0 - 1 : nil }) {
|
||||
nums[j + 1] = nums[j]
|
||||
}
|
||||
nums[index] = num
|
||||
// 更新元素数量
|
||||
_size += 1
|
||||
}
|
||||
|
||||
/* 删除元素 */
|
||||
@discardableResult
|
||||
func remove(index: Int) -> Int {
|
||||
if index < 0 || index >= _size {
|
||||
fatalError("索引越界")
|
||||
}
|
||||
let num = nums[index]
|
||||
// 将索引 index 之后的元素都向前移动一位
|
||||
for j in index ..< (_size - 1) {
|
||||
nums[j] = nums[j + 1]
|
||||
}
|
||||
// 更新元素数量
|
||||
_size -= 1
|
||||
// 返回被删除元素
|
||||
return num
|
||||
}
|
||||
|
||||
/* 列表扩容 */
|
||||
func extendCapacity() {
|
||||
// 新建一个长度为 size 的数组,并将原数组拷贝到新数组
|
||||
nums = nums + Array(repeating: 0, count: _capacity * (extendRatio - 1))
|
||||
// 更新列表容量
|
||||
_capacity = nums.count
|
||||
}
|
||||
}
|
||||
[class]{MyList}-[func]{}
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
Reference in New Issue
Block a user