-
Notifications
You must be signed in to change notification settings - Fork 108
/
Stack2.kt
53 lines (43 loc) · 1.15 KB
/
Stack2.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.util.LinkedList
/**
*
* 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:
*
* push() - when we insert an element in a stack then the operation is known as a push.
* pop() - when we delete an element from the stack, the operation is known as a pop.
* If the stack is empty means that no element exists in the stack.
*
* All these operations performed in O(1) time.
*
*/
class Stack2<T> {
// this implementation uses LinkedList
private val data = LinkedList<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.peekLast()
}
fun clear() {
data.clear()
}
}