Why does line 6 still prints "A" here, see <https:...
# announcements
t
Why does line 6 still prints "A" here, see https://stackoverflow.com/questions/62595494/linkedlist-remove-element-puzzle
Copy code
fun main(args: Array<String>) {
        var tree = Node("A", null, null)
        val q: Queue<Node> = LinkedList()
        q.add(tree)
        tree = q.remove() // line 5, remove element in q and assign to tree so tree so should size 0
        println(tree.data) // line 6, why does this still print "A" though?
}
// given
class Node {
    var data: String
    var left: Node? = null
    var right: Node? = null

    constructor(data: String) {
        this.data = data
    }

    constructor(data: String, left: Node?, right: Node?) {
        this.data = data
        this.left = left
        this.right = right
    }
}
d
You only ever create one
Tree
object. You put it into the queue and then get it back out, but it's still the same
Node
object
t
huh? im still confuse. does this mean this line does nothing then?
tree = q.remove() // line 5
d
Well it removes the first element from the list, which happens to be the same as
tree
. So what it does is change the list contents
But it does not change the object thats stored in
tree
m
you create Node and name it tree you make a list you put the node (tree) in the list you remove the node(tree) and assign that node to tree (tree = tree)
so yeah,
q.remove()
removes a node from it's queue, but returns it for you. and you assigned that into your
var tree
t
yea
tree
is declared as var so it should take the content of
q.remove()
and q.remove() removed the content
m
and returns that content
t
so
tree
shoudl have no content?
m
no you dont understand
look what the
q.remove()
statement does
t
yea
i see
i missed the bit that said
return removeFirst();
thanks