This commit is contained in:
krahets
2024-03-25 22:43:12 +08:00
parent 22017aa8e5
commit 87af663929
70 changed files with 7428 additions and 32 deletions

View File

@ -130,6 +130,12 @@ comments: true
// C 未提供内置动态数组
```
=== "Kotlin"
```kotlin title="list.kt"
```
=== "Zig"
```zig title="list.zig"
@ -253,6 +259,12 @@ comments: true
// C 未提供内置动态数组
```
=== "Kotlin"
```kotlin title="list.kt"
```
=== "Zig"
```zig title="list.zig"
@ -478,6 +490,12 @@ comments: true
// C 未提供内置动态数组
```
=== "Kotlin"
```kotlin title="list.kt"
```
=== "Zig"
```zig title="list.zig"
@ -669,6 +687,12 @@ comments: true
// C 未提供内置动态数组
```
=== "Kotlin"
```kotlin title="list.kt"
```
=== "Zig"
```zig title="list.zig"
@ -782,6 +806,12 @@ comments: true
// C 未提供内置动态数组
```
=== "Kotlin"
```kotlin title="list.kt"
```
=== "Zig"
```zig title="list.zig"
@ -877,6 +907,12 @@ comments: true
// C 未提供内置动态数组
```
=== "Kotlin"
```kotlin title="list.kt"
```
=== "Zig"
```zig title="list.zig"
@ -2035,6 +2071,106 @@ comments: true
}
```
=== "Kotlin"
```kotlin title="my_list.kt"
/* 列表类 */
class MyList {
private var arr: IntArray = intArrayOf() // 数组(存储列表元素)
private var capacity = 10 // 列表容量
private var size = 0 // 列表长度(当前元素数量)
private var extendRatio = 2 // 每次列表扩容的倍数
/* 构造函数 */
init {
arr = IntArray(capacity)
}
/* 获取列表长度(当前元素数量) */
fun size(): Int {
return size
}
/* 获取列表容量 */
fun capacity(): Int {
return capacity
}
/* 访问元素 */
fun get(index: Int): Int {
// 索引如果越界,则抛出异常,下同
if (index < 0 || index >= size)
throw IndexOutOfBoundsException()
return arr[index]
}
/* 更新元素 */
fun set(index: Int, num: Int) {
if (index < 0 || index >= size)
throw IndexOutOfBoundsException("索引越界")
arr[index] = num
}
/* 在尾部添加元素 */
fun add(num: Int) {
// 元素数量超出容量时,触发扩容机制
if (size == capacity())
extendCapacity()
arr[size] = num
// 更新元素数量
size++
}
/* 在中间插入元素 */
fun insert(index: Int, num: Int) {
if (index < 0 || index >= size)
throw IndexOutOfBoundsException("索引越界")
// 元素数量超出容量时,触发扩容机制
if (size == capacity())
extendCapacity()
// 将索引 index 以及之后的元素都向后移动一位
for (j in size - 1 downTo index)
arr[j + 1] = arr[j]
arr[index] = num
// 更新元素数量
size++
}
/* 删除元素 */
fun remove(index: Int): Int {
if (index < 0 || index >= size)
throw IndexOutOfBoundsException("索引越界")
val num: Int = arr[index]
// 将将索引 index 之后的元素都向前移动一位
for (j in index..<size - 1)
arr[j] = arr[j + 1]
// 更新元素数量
size--
// 返回被删除的元素
return num
}
/* 列表扩容 */
fun extendCapacity() {
// 新建一个长度为原数组 extendRatio 倍的新数组,并将原数组复制到新数组
arr = arr.copyOf(capacity() * extendRatio)
// 更新列表容量
capacity = arr.size
}
/* 将列表转换为数组 */
fun toArray(): IntArray {
val size = size()
// 仅转换有效长度范围内的列表元素
val arr = IntArray(size)
for (i in 0..<size) {
arr[i] = get(i)
}
return arr
}
}
```
=== "Zig"
```zig title="my_list.zig"