-
Notifications
You must be signed in to change notification settings - Fork 88
/
Copy pathQueue.kt
74 lines (57 loc) · 1.49 KB
/
Queue.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
/**
* Created by gazollajunior on 05/04/16.
*/
class Queue <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()
override fun toString() = this.items.toString()
fun enqueue(element: T){
this.items.add(element)
}
fun dequeue():T?{
if (this.isEmpty()){
return null
} else {
return this.items.removeAt(0)
}
}
fun peek():T?{
return this.items[0]
}
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 queue = Queue<Int>(initialValue)
println(queue)
queue.enqueue(22)
println(queue)
queue.enqueue(55)
println(queue)
queue.enqueue(77)
println(queue)
queue.dequeue()
println(queue)
queue.dequeue()
println(queue)
queue.dequeue()
println(queue)
// Iterating over queue
for (item in queue) println("Item in queue : " + item)
}