# Why do I get Runtime error?

• In "Remove Linked List Elements", I use double pointer to delete an element like how it's done in two star pointer.
My code is:

``````void deleteNode(ListNode* node) {
ListNode **curr = &node;
ListNode *temp = *curr;
(*curr) = (*curr)->next;
delete temp;
}
``````

But I get runtime error for the following input:

Last executed input:
[0,0,0], node at index 0 (node.val = 0)

I'm quite confused. Does anyone know why?

• Why do you keep it a secret which test case you fail? Why make it hard for others to help you?

Anyway... your code does exactly the same as the following (*), except in an extremely convoluted way.

``````void deleteNode(ListNode* node) {
delete node;
}
``````

This of course can't work. You can't just delete an element in the list. The previous node will then point to an invalid address. This is asking for a crash.

(*) At least if `node` is a valid pointer (not null), which is the case in the problem here.

• Sorry, this is my first time to ask a question. I have modified my question. But I still don't understand.

You mean (*curr) = (*curr)->next; has no effect. But why it works in the link I added?
Would you like to explain more?

• Let's reduce this step by step.

``````void deleteNode(ListNode* node) {
ListNode **curr = &node;
ListNode *temp = *curr;
(*curr) = (*curr)->next;
delete temp;
}
``````

Well, `curr` is `&node`, so `*curr` is `*&node` which is just `node`. So let's get rid of `curr`:

``````void deleteNode(ListNode* node) {
ListNode *temp = node;
node = node->next;
delete temp;
}
``````

Setting `node = node->next;` has no effect, as that just changes your local variable. And you're not even using that variable afterwards. Let's remove that line.

``````void deleteNode(ListNode* node) {
ListNode *temp = node;
delete temp;
}
``````

Since `temp` is just another name for `node`, let's get rid of it.

``````void deleteNode(ListNode* node) {
delete node;
}
``````

Now, why does that other solution work? Because there the `ListNode**` points to a pointer that's actually part of the list - either the `head` pointer or the `next` field of a list node. Not just to an outside variable like in your case here. And it returns `head`, that's how the caller gets to know about it if the head node got deleted.

That other solution should btw also `delete` properly. It's leaking memory.

• I understand. Thank you for your kind reply.

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