I am having a hard time grasping the append()
method when trying to learn about basic LinkedList implementation:
class LinkedList(value : Int) {
private var head : Node = Node()
private var tail : Node
private var length : Int = 0
init {
head.value = value
tail = head
length
}
fun append(value: Int): LinkedList {
val newNode = Node(value)
tail.next = newNode
tail = newNode
length
return this
}
override fun toString(): String {
return "LinkedList {\nhead: $head,\ntail: $tail,\nlength: $length }"
}
class Node(var value : Int = -1, var next : Node? = null) {
override fun toString(): String {
return "Node { value: $value next: $next }"
}
}
}
As you can see in my implementation, when using the append()
method we assign tail.next
to the newNode
that we created. The thing is that tail.next
is head.next
, since at the init block we initialized tail = head
, therefore I can't understand why in the append()
method we can't do head.next = newNode
instead of tail.next = newNode
.
Technically I know what would happen - we would not advance any further than one time and just rewrite the same node over and over, but I am finding it really hard to understand why since at the init { }
block we declared tail
to point to the same address in memory that head
is, therefore anyway what we are doing is advancing the head.next
over and over, so why not use it in the first place?