Skip to content

Commit 3e831c0

Browse files
committed
Add Stack
1 parent 3c76768 commit 3e831c0

File tree

1 file changed

+23
-0
lines changed
  • src/test/kotlin/com/igorwojda/tree/multiway/traversal

1 file changed

+23
-0
lines changed

src/test/kotlin/com/igorwojda/tree/multiway/traversal/Challenge.kt

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,29 @@ private class Queue<E> {
120120
val size get() = list.size
121121
}
122122

123+
/*
124+
Stack can be used as helper class to implement depth first traversal. This is not the most optimal stack implementation,
125+
however it's enough for this task. Check "Queue challenge" solution for more details and more efficient stack
126+
implementation.
127+
*/
128+
private class Stack<E> {
129+
private val list = mutableListOf<E>()
130+
131+
val size get() = list.size
132+
133+
fun add(element: E) {
134+
list.add(element)
135+
}
136+
137+
fun remove() = if (list.isEmpty()) null else list.removeAt(list.lastIndex)
138+
139+
fun peek() = list.lastOrNull()
140+
141+
fun isEmpty() = list.isEmpty()
142+
143+
fun isNotEmpty() = list.isNotEmpty()
144+
}
145+
123146
private class Test {
124147
@Test
125148
fun `traverse breath first`() {

0 commit comments

Comments
 (0)