Stack与LinkedList如何在Kotlin中实现
作者
这篇文章将为大家详细讲解有关Stack与LinkedList如何在Kotlin中实现,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
Stack
Java中Stack由List实现,Kotlin中有MutableList,Stack类的基本定义如下,继承Iterator为了迭代遍历:
classStack<T:Comparable<T>>(list:MutableList<T>):Iterator<T>
基本属性实现
//stack的count varitCounter:Int=0 //stack内部实现为MutableList varitems:MutableList<T>=list //判断stack是否为null funisEmpty():Boolean=this.items.isEmpty() //获取stack的itemscounte funcount():Int=this.items.count() //tostring操作 overridefuntoString():String{ returnthis.items.toString() }
基本操作实现
//pop操作,弹出栈顶元素即链表最末端元素,可为null funpop():T?{ if(this.isEmpty()){ returnnull }else{ valitem=this.items.count()-1 returnthis.items.removeAt(item) } } //只读操作,不弹出 funpeek():T?{ if(isEmpty()){ returnnull }else{ returnthis.items[this.items.count()-1] } } //hasNext操作 overridefunhasNext():Boolean{ valhasNext=itCounter<count() if(!hasNext)itCounter=0 returnhasNext } //取next元素 overridefunnext():T{ if(hasNext()){ valtopPos:Int=(count()-1)-itCounter itCounter++ returnthis.items[topPos] }else{ throwNoSuchElementException("Nosuchelement")//异常不用new哦 } }
LinkedList
LinkedList的实现需要Node,然后实现first、last、count以及append等操作。
Node 定义
classNode<T>(value:T){ varvalue:T=value//value可以是任意类型 varnext:Node<T>?=null//next可以为null varprevious:Node<T>?=null//pre也可以为null }
基本操作一
//头结点,引导性作用 varhead:Node<T>?=null //取决于head是否为null varisEmpty:Boolean=head==null //获取first funfirst():Node<T>?=head //获取last结点,需要一直next才能到达last结点 funlast():Node<T>?{ varnode=head if(node!=null){ while(node?.next!=null){ node=node?.next } returnnode }else{ returnnull } }
基本操作二
//获取count,同样通过next计算 funcount():Int{ varnode=head if(node!=null){ varcounter=1 while(node?.next!=null){ node=node?.next counter+=1 } returncounter }else{ return0 } } //append操作,在last结点上append funappend(value:T){ varnewNode=Node(value) //获取当前节点的最后一个节点 varlastNode=this.last() if(lastNode!=null){ newNode.previous=lastNode lastNode.next=newNode }else{ head=newNode } } //删除操作 funremoveNode(node:Node<T>):T{ valprev=node.previous valnext=node.next if(prev!=null){ prev.next=next }else{ head=next } next?.previous=prev node.previous=null//将断开的节点前后置null node.next=null returnnode.value//返回删除节点的value }
关于Stack与LinkedList如何在Kotlin中实现就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
目录
推荐阅读
-
Linux中如何安装和使用 Kotlin 开发环境
-
go语言和kotlin的区别是什么
go语言和kotlin的区别是什么本篇内容主要讲解“go语言和ko...
-
kotlin顶层函数和函数表达式怎么用
kotlin顶层函数和函数表达式怎么用这篇文章将为大家详细讲解有关...
-
静态变量与静态方法怎么在Kotlin中使用
这期内容当中小编将会给大家带来有关静态变量与静态方法怎么在Kotlin中使用,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这...
-
怎么在Kotlin中使用Lambda设置回调作
今天就跟大家聊聊有关怎么在Kotlin中使用Lambda设置回调作,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下...
-
如何在Kotlin中使用对象表达式和对象声明
这期内容当中小编将会给大家带来有关如何在Kotlin中使用对象表达式和对象声明,文章内容丰富且以专业的角度为大家分析和叙述,阅读完...