-
Notifications
You must be signed in to change notification settings - Fork 109
/
Stack1.kt
53 lines (43 loc) · 1.11 KB
/
Stack1.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
package structures
import java.lang.IllegalArgumentException
import java.util.ArrayList
/**
*
* Stack is a linear data structure that follows the LIFO (last in first out) principle
*
* LIFO implies that the element that is inserted last, comes out first.
*
* The main operations:
*
* 1) push() - when we insert an element in a stack then the operation is known as a push
* 2) pop() - when we delete an element from the stack, the operation is known as a pop
*
* All these operations performed in O(1) time.
*
*/
class Stack1<T> {
// this implementation uses ArrayList
private val data = ArrayList<T>()
val isEmpty: Boolean
get() = data.size == 0
val size: Int
get() = data.size
fun push(item: T) {
data.add(item)
}
fun pop() : T {
if (isEmpty) {
throw IllegalArgumentException("Stack is empty!")
}
return data.removeLast()
}
fun peek() : T {
if (isEmpty) {
throw IllegalArgumentException("Stack is empty!")
}
return data.last()
}
fun clear() {
data.clear()
}
}