-
Notifications
You must be signed in to change notification settings - Fork 108
/
Queue.kt
51 lines (39 loc) · 1.06 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
package structures
import java.util.LinkedList
/**
*
* Queue is a data structure that follows the FIFO (first in, first out) principle
*
* LIFO implies that the element that is inserted first, comes out first
*
* The main operations:
*
* 1) enqueue - inserts an element at the end of the queue
* 2) dequeue - removes an element from the beginning of the queue
*
* All these operations performed in O(1) time.
*
*/
class Queue<T> {
private val data = LinkedList<T>()
val isEmpty: Boolean
get() = data.isEmpty()
val size: Int
get() = data.size
fun enqueue(item: T) {
data.add(item)
}
fun dequeue(): T {
if (isEmpty) throw IllegalStateException("The queue is empty")
// LinkedList under the hood stores a link to the first element
// this operation will be completed in time O(1)
return data.removeFirst()
}
fun peek(): T {
if (isEmpty) throw IllegalStateException("The queue is empty")
return data.first
}
fun clear() {
data.clear()
}
}