-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.kt
More file actions
67 lines (54 loc) · 1.41 KB
/
Stack.kt
File metadata and controls
67 lines (54 loc) · 1.41 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package datastruct
/*
栈
*/
class Stack<T> : Iterator<T>{
//stack的count
var elementCount: Int = 0
//stack内部实现为MutableList
var items: MutableList<T> = mutableListOf()
//判断Stack是否为null
fun isEmpty(): Boolean = this.items.isEmpty()
//获取statck的items count
fun count(): Int = this.items.count()
override fun toString(): String {
return this.items.toString()
}
fun push(item: T): T?{
elementCount++
items.add(item)
return item
}
//pop操作,弹出栈顶元素即链表最末端元素,可为null
fun pop(): T?{
if (this.isEmpty()){
return null
}else{
elementCount--
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]
}
}
override fun hasNext(): Boolean {
val hasNext = elementCount < count()
if (!hasNext) elementCount = 0
return hasNext
}
override fun next(): T {
if (hasNext()){
val topPos: Int = (count() - 1) - elementCount
elementCount++
return this.items[topPos]
}else{
throw NoSuchElementException("No such element")
}
}
}