File tree Expand file tree Collapse file tree 1 file changed +74
-0
lines changed
Expand file tree Collapse file tree 1 file changed +74
-0
lines changed Original file line number Diff line number Diff line change 1+ import kotlin.Array
2+
3+ /* *
4+ * 1) 数组的插入、删除、按照下标随机访问操作;
5+ * 2)数组中的数据是int类型的;
6+ *
7+ * Author: Zackratos
8+ */
9+
10+ class ArrayKt constructor(private val capacity : Int ) {
11+ // 定义整型数据data保存数据
12+ private val data: IntArray = IntArray (capacity)
13+ // 定义数组中实际个数
14+ private var count: Int = 0
15+
16+ companion object {
17+ @JvmStatic
18+ fun main (args : Array <String >) {
19+ val array = ArrayKt (5 )
20+ array.printAll()
21+ array.insert(0 , 3 )
22+ array.insert(0 , 4 )
23+ array.insert(1 , 5 )
24+ array.insert(3 , 9 )
25+ array.insert(3 , 10 )
26+ array.printAll()
27+ }
28+ }
29+
30+ // 根据索引,找到数据中的元素并返回
31+ fun find (index : Int ): Int {
32+ if (index !in 0 .. (count - 1 )) return - 1
33+ return data[index]
34+ }
35+
36+ // 插入元素:头部插入,尾部插入
37+ fun insert (index : Int , value : Int ): Boolean {
38+ // 数组空间已满
39+ if (count == capacity) {
40+ System .out .println (" 没有可插入的位置" )
41+ return false
42+ }
43+ // 如果count还没满,那么就可以插入数据到数组中
44+ // 位置不合法
45+ if (index !in 0 .. count) {
46+ System .out .println (" 位置不合法" )
47+ return false
48+ }
49+ // 位置合法
50+ (count downTo index + 1 ).forEach {
51+ data[it] = data[it - 1 ]
52+ }
53+ data[index] = value
54+ ++ count
55+ return true
56+ }
57+
58+ // 根据索引,删除数组中元素
59+ fun delete (index : Int ): Boolean {
60+ if (index !in 0 .. (count - 1 )) return false
61+ (index + 1 until count).forEach {
62+ data[it - 1 ] = data[it]
63+ }
64+ -- count
65+ return true
66+ }
67+
68+ fun printAll () {
69+ (0 until count).forEach {
70+ System .out .println (" ${data[it]} " )
71+ }
72+ }
73+
74+ }
You can’t perform that action at this time.
0 commit comments