-
Notifications
You must be signed in to change notification settings - Fork 0
/
Linked list
54 lines (40 loc) · 935 Bytes
/
Linked list
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
class LinkedList<T> {
private var head: Node<T>? = null
private var tail: Node<T>? = null
private var size = 0
fun isEmpty(): Boolean {
return size == 0
}
override fun toString(): String {
if (isEmpty()) {
return "Empty list"
} else {
return head.toString()
}
}
class Node<T>(val value: T) {
var next: Node<T>? = null
}
class LinkedList<T> {
private var head: Node<T>? = null
fun push(value: T) {
val node = Node(value)
node.next = head
head = node
}
fun pop(): T? {
if (head == null) return null
val value = head!!.value
head = head!!.next
return value
}
override fun toString(): String {
var current = head
var str = ""
while (current != null) {
str += "${current.value} -> "
current = current.next
}
return str + "null"
}
}