Stack与LinkedList如何在Kotlin中实现-创新互联
这篇文章将为大家详细讲解有关Stack与LinkedList如何在Kotlin中实现,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

Stack
Java中Stack由List实现,Kotlin中有MutableList,Stack类的基本定义如下,继承Iterator为了迭代遍历:
class Stack>(list : MutableList ) : Iterator
基本属性实现
// stack的count var itCounter: Int = 0 // stack内部实现为MutableList var items: MutableList= list // 判断stack是否为null fun isEmpty(): Boolean = this.items.isEmpty() // 获取stack的items counte fun count(): Int = this.items.count() // tostring操作 override fun toString(): String { return this.items.toString() }
基本操作实现
// pop操作,弹出栈顶元素即链表最末端元素,可为null
fun pop(): T? {
if (this.isEmpty()) {
return null
} else {
val item = this.items.count() - 1
return this.items.removeAt(item)
}
}
// 只读操作,不弹出
fun peek(): T? {
if (isEmpty()) {
return null
} else {
return this.items[this.items.count() - 1]
}
}
// hasNext操作
override fun hasNext(): Boolean {
val hasNext = itCounter < count()
if (!hasNext) itCounter = 0
return hasNext
}
// 取next元素
override fun next(): T {
if (hasNext()){
val topPos : Int = (count() - 1) - itCounter
itCounter++
return this.items[topPos]
}else{
throw NoSuchElementException("No such element") // 异常不用new哦
}
}LinkedList
LinkedList的实现需要Node,然后实现first、last、count以及append等操作。
Node 定义
class Node(value : T){ var value : T = value // value可以是任意类型 var next : Node ? = null // next可以为null var previous : Node ? = null // pre也可以为null }
基本操作一
// 头结点,引导性作用 var head : Node?= null // 取决于head是否为null var isEmpty : Boolean = head == null // 获取first fun first() : Node ? = head // 获取last结点,需要一直next才能到达last结点 fun last() : Node ?{ var node = head if (node != null){ while (node?.next != null){ node = node?.next } return node }else{ return null } }
基本操作二
// 获取count,同样通过next计算
fun count():Int {
var node = head
if (node != null){
var counter = 1
while (node?.next != null){
node = node?.next
counter += 1
}
return counter
} else {
return 0
}
}
// append操作,在last结点上append
fun append(value : T){
var newNode = Node(value)
// 获取当前节点的最后一个节点
var lastNode = this.last()
if (lastNode != null){
newNode.previous = lastNode
lastNode.next = newNode
}else{
head = newNode
}
}
// 删除操作
fun removeNode(node : Node) : T{
val prev = node.previous
val next = node.next
if (prev != null){
prev.next = next
}else{
head = next
}
next?.previous = prev
node.previous = null // 将断开的节点前后置null
node.next = null
return node.value // 返回删除节点的value
} 关于Stack与LinkedList如何在Kotlin中实现就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
网页题目:Stack与LinkedList如何在Kotlin中实现-创新互联
文章链接:http://www.jxjierui.cn/article/iijjs.html


咨询
建站咨询
