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

@ -306,6 +306,12 @@ comments: true
// C 未提供内置栈
```
=== "Kotlin"
```kotlin title="stack.kt"
```
=== "Zig"
```zig title="stack.zig"
@ -1008,6 +1014,60 @@ comments: true
}
```
=== "Kotlin"
```kotlin title="linkedlist_stack.kt"
/* 基于链表实现的栈 */
class LinkedListStack(
private var stackPeek: ListNode? = null, // 将头节点作为栈顶
private var stkSize: Int = 0 // 栈的长度
) {
/* 获取栈的长度 */
fun size(): Int {
return stkSize
}
/* 判断栈是否为空 */
fun isEmpty(): Boolean {
return size() == 0
}
/* 入栈 */
fun push(num: Int) {
val node = ListNode(num)
node.next = stackPeek
stackPeek = node
stkSize++
}
/* 出栈 */
fun pop(): Int? {
val num = peek()
stackPeek = stackPeek?.next
stkSize--;
return num
}
/* 访问栈顶元素 */
fun peek(): Int? {
if (isEmpty()) throw IndexOutOfBoundsException()
return stackPeek?.value
}
/* 将 List 转化为 Array 并返回 */
fun toArray(): IntArray {
var node = stackPeek
val res = IntArray(size())
for (i in res.size - 1 downTo 0) {
res[i] = node?.value!!
node = node.next
}
return res
}
}
```
=== "Zig"
```zig title="linkedlist_stack.zig"
@ -1643,6 +1703,48 @@ comments: true
}
```
=== "Kotlin"
```kotlin title="array_stack.kt"
/* 基于数组实现的栈 */
class ArrayStack {
// 初始化列表(动态数组)
private val stack = ArrayList<Int>()
/* 获取栈的长度 */
fun size(): Int {
return stack.size
}
/* 判断栈是否为空 */
fun isEmpty(): Boolean {
return size() == 0
}
/* 入栈 */
fun push(num: Int) {
stack.add(num)
}
/* 出栈 */
fun pop(): Int {
if (isEmpty()) throw IndexOutOfBoundsException()
return stack.removeAt(size() - 1)
}
/* 访问栈顶元素 */
fun peek(): Int {
if (isEmpty()) throw IndexOutOfBoundsException()
return stack[size() - 1]
}
/* 将 List 转化为 Array 并返回 */
fun toArray(): Array<Any> {
return stack.toArray()
}
}
```
=== "Zig"
```zig title="array_stack.zig"