前言
本文主要介紹的是關于Kotlin 實現基本的數據結構 Stack 和 LinkedList,分享出來供大家參考學習,下面話不多說了,來一起看看詳細的介紹吧。
Stack
Java中Stack由List實現,Kotlin中有MutableList,Stack類的基本定義如下,繼承Iterator為了迭代遍歷:
1
|
class Stack<T : Comparable<T>>(list : MutableList<T>) : Iterator<T> |
基本屬性實現
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
// 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() } |
基本操作實現
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
// 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 定義
1
2
3
4
5
|
class Node<T>(value : T){ var value : T = value // value可以是任意類型 var next : Node<T>? = null // next可以為null var previous : Node<T>? = null // pre也可以為null } |
基本操作一
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
// 頭結點,引導性作用 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 } } |
基本操作二
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
// 獲取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 } |
以上,用kotlin實現基本的數據結構stack和linkedlist.
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。
原文鏈接:https://allenwu.itscoder.com/datastructure-in-kotlin