Stack与LinkedList如何在Kotlin中实现

发布时间:2021-04-07 17:40:21 作者:Leah
来源:亿速云 阅读:218

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

Stack

Java中Stack由List实现,Kotlin中有MutableList,Stack类的基本定义如下,继承Iterator为了迭代遍历:

class Stack<T : Comparable<T>>(list : MutableList<T>) : Iterator<T>

基本属性实现

// stack的count
 var itCounter: Int = 0

// stack内部实现为MutableList
 var items: MutableList<T> = 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<T>(value : T){
 var value : T = value // value可以是任意类型
 var next : Node<T>? = null // next可以为null
 var previous : Node<T>? = null // pre也可以为null
}

基本操作一

// 头结点,引导性作用
var head : Node<T>?= null

// 取决于head是否为null
var isEmpty : Boolean = head == null

// 获取first
fun first() : Node<T>? = head

// 获取last结点,需要一直next才能到达last结点
fun last() : Node<T>?{
 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>) : 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中实现就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. JAVA自己实现LinkedList
  2. 如何在Java中使用LinkedList

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

kotlin linkedlist stack

上一篇:怎么在Python项目中实现一个字典迭代

下一篇:怎么在Android中利用NestedScrolling实现嵌套滚动

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》