-
Notifications
You must be signed in to change notification settings - Fork 88
/
Copy pathStack.kt
92 lines (70 loc) · 1.93 KB
/
Stack.kt
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/**
* Created by gazollajunior on 03/04/16.
*/
class Stack<T:Comparable<T>>(list:MutableList<T>):Iterator<T> {
var itCounter: Int = 0
var items: MutableList<T> = list
fun isEmpty():Boolean = this.items.isEmpty()
fun count():Int = this.items.count()
fun push(element:T) {
val position = this.count()
this.items.add(position, element)
}
override fun toString() = this.items.toString()
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]
}
}
// Note Let the default implementation exist
// override fun toString(): String {
// val topDivider = "---Stack---\n"
// val bottomDivider = "\n-----------"
//
// val stackElements = array.map {
// "$it"
// }.reversed().joinToString("\n")
//
// return topDivider + stackElements + bottomDivider
//
// }
override fun hasNext(): Boolean {
val hasNext = itCounter < count()
// As soon as condition fails, reset the counter
if (!hasNext) itCounter = 0
return hasNext
}
override fun next(): T {
if (hasNext()) {
val topPos: Int = (count() - 1) - itCounter
itCounter++
return this.items[topPos]
} else {
throw NoSuchElementException("No such element")
}
}
}
fun main(args: Array<String>) {
var initialValue = mutableListOf<Int>(10)
var stack = Stack<Int>(initialValue)
println(stack)
stack.push(22)
println(stack)
stack.push(55)
println(stack)
stack.push(77)
println(stack)
stack.pop()
println(stack)
for (item in stack) println("Item in stack : " + item)
}