-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStack.kt
112 lines (91 loc) · 2.26 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package structures
import java.lang.IllegalArgumentException
import kotlin.collections.ArrayList
/**
* data structure: stack
*
* description: the stack uses the LIFO principle (last in, first out), all operations are performed in O(1) time
*
*/
interface Stack<T> {
/**
* adds an element to the top of the stack
*
* @param item - element
*/
fun push(item: T)
/**
* removes the element at the top of the stack and returns it
*
*/
fun pop() : T
/**
* returns the element at the top of the stack without removing
*
*/
fun peek() : T
/**
* returns true if the stack is empty
*
*/
fun isEmpty() : Boolean
/**
* clears the stack
*
*/
fun clear()
/**
* implementation using ArrayList
*
* @param T - stack element type
*/
class ArrayListStack<T> : Stack<T> {
private val data = ArrayList<T>()
override fun push(item: T) {
data.add(item)
}
override fun pop() : T {
if (isEmpty()) {
throw IllegalArgumentException("Stack is empty!")
}
return data.removeLast()
}
override fun peek() : T {
if (isEmpty()) {
throw IllegalArgumentException("Stack is empty!")
}
return data.last()
}
override fun isEmpty() = data.isEmpty()
override fun clear() {
data.clear()
}
}
/**
* linked list implementation
*
* @param T - тип элементов стэка
*/
class LinkedListStack<T> : Stack<T> {
private val data = java.util.LinkedList<T>()
override fun push(item: T) {
data.add(item)
}
override fun pop(): T {
if (isEmpty()) {
throw IllegalArgumentException("Stack is empty!")
}
return data.removeLast()
}
override fun peek(): T {
if (isEmpty()) {
throw IllegalArgumentException("Stack is empty!")
}
return data.peekLast()
}
override fun isEmpty() = data.isEmpty()
override fun clear() {
data.clear()
}
}
}