如何在Kotlin中使用Stack (来自java)?
或者还有别的选择?
发布于 2020-01-10 07:27:47
import java.util.ArrayDeque
var stack = ArrayDeque<Int>()
stack.push(1)
stack.push(2)
stack.push(3)
stack.push(4)
println(stack) // --> [4, 3, 2, 1]
println(stack.isEmpty()) // --> false
println(stack.peek()) // --> 4
println(stack) // --> [4, 3, 2, 1]
println(stack.pop()) // --> 4
println(stack) // --> [3, 2, 1]
stack.push(9)
println(stack) // --> [9, 3, 2, 1]发布于 2021-06-14 04:08:33
Kotlin 1.3.70引入了kotlin.collections.ArrayDeque类,它既是队列又是堆栈,如java.util.Deque (Deque的意思是“双结束队列”)。它的创建是出于多平台ArrayDeque实现的需要。
val stack = ArrayDeque(listOf(1, 2, 3)) // stack: [1, 2, 3]
stack.addLast(0) // stack: [1, 2, 3, 0] (push)
val value = stack.removeLast() // value: 0, stack: [1, 2, 3] (pop)注意,如果一个ArrayDeque在调用removeFirst或removeLast时为空,它将抛出一个kotlin.NoSuchElementException。如果您不想每次需要访问deque时检查deque的大小,那么应该使用removeFirstOrNull和removeLastOrNull函数。
可选片段
ArrayDeque构造函数:
inline fun <T> arrayDequeOf(vararg elements: T) = ArrayDeque(elements.toList())
// ...
val stack = arrayDequeOf(1, 2, 3)Stack-like ArrayDeque调用:
inline fun <T> ArrayDeque<T>.push(element: T) = addLast(element) // returns Unit
inline fun <T> ArrayDeque<T>.pop() = removeLastOrNull() // returns T?发布于 2020-05-11 07:22:17
您可以使用以下方法:
/**
* Stack as type alias of Mutable List
*/
typealias Stack<T> = MutableList<T>
/**
* Pushes item to [Stack]
* @param item Item to be pushed
*/
inline fun <T> Stack<T>.push(item: T) = add(item)
/**
* Pops (removes and return) last item from [Stack]
* @return item Last item if [Stack] is not empty, null otherwise
*/
fun <T> Stack<T>.pop(): T? = if (isNotEmpty()) removeAt(lastIndex) else null
/**
* Peeks (return) last item from [Stack]
* @return item Last item if [Stack] is not empty, null otherwise
*/
fun <T> Stack<T>.peek(): T? = if (isNotEmpty()) this[lastIndex] else nullhttps://stackoverflow.com/questions/46900048
复制相似问题