简体   繁体   中英

LinkedList remove element puzzle

I'm confuse about why line 6 still prints "A" even though I remove the only element in list in line 5. Could someone please explain what is happening here?

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
        }
    }

Seems like LinkedList.remove() is returning the head of it before it remove the head. Here is the link to java 8 source code of LinkedList: https://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/LinkedList.java

It will call the E unlinkFirst(Node<E> f) method (line 171), and returning the element before it delete.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM