-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackStructure.kt
More file actions
62 lines (53 loc) · 1.14 KB
/
StackStructure.kt
File metadata and controls
62 lines (53 loc) · 1.14 KB
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
package dataStructures.stack
/**
* Implementation of the stack data structure
*
* @param E the type of the elements in the stack
*/
class StackStructure<E> : Stack<E> {
/**
* Node class for the stack
*
* @param value the value of the node
* @param next the next node
*/
class Node<E>(val value: E?, val next: Node<E>?)
private val sentinel: Node<E>? = null
var currentNode = sentinel
/**
* Pushes a new element to the stack
*
* @param new the new element to be pushed
*/
override fun push(new: E) {
val nodeToAdd = Node(new, currentNode)
currentNode = nodeToAdd
}
/**
* Pops the top element from the stack
*
* @return the top element from the stack
*/
override fun pop(): E? {
if (isEmpty()) return null
val nodeToRemove = peek()
currentNode = currentNode?.next
return nodeToRemove
}
/**
* Peeks the top element from the stack
*
* @return the top element from the stack
*/
override fun peek(): E? {
return currentNode?.value
}
/**
* Checks if the stack is empty
*
* @return true if the stack is empty, false otherwise
*/
override fun isEmpty(): Boolean {
return currentNode == null
}
}