Java Solution (Is there a way not to change the value inside the node?)

  • 2

    Just wondering is there a way not to change the value inside the node?

    public class Solution {
        public void deleteNode(ListNode node) {
            if(node == null) return;
            node.val =;

  • 3

    Well, the reference pointing to the given node must afterwards point to a node with the value of the next node. So if you don't change the value, I think you must change the reference.

    Of course, the reference is in the previous node, or if we're asked to delete the lists's head, the reference is perhaps a variable in the OJ code. And we have neither of those. Maybe we can find it by asking the runtime environment somehow. Just for fun I actually tried that in Python with gc.get_referrers(node), going through what the garbage collector tracks. And changing references to the node to instead reference the next node. It works in my script on my PC, but I couldn't get it to work in the OJ here. But it's a hack anyway and I don't really know what I'm doing :-)

    Anyway, most certainly the indended solution is what you did, copying the data from the next node and deleting that one instead.

  • 0

    I learnt quite a bit from you. You are awesome.

  • 0

    I learnt quite a bit from you.

    Glad to hear that :-)

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.