Click here to see the full article post
Wait..where did the 5 come from? If it was the original 1 --> 2 --> 3 --> 4 list then 4 (node.next) would be pointing to nothing (node.next.next).
GHOST-44, do you mean that if we try to remove the last element, program crash, because there is no next element after the last or?
@elmirap Yes, you would get a NullPointerException, no?
@GHOST-44 could be correct, unless it wasn't said that we delete all nodes with the exception of tail (last element)
Lol I was stumped first two minutes when I've been thinking of this question. And when I've finally came up with a solution I was like facepalm as it turned out to be so easy! I really enjoyed this question, it's very easy but it's not just trivial as many of easy tasks here. Thank you!
@ivan70 I also find leetcode questions to be very interesting and tricky. You could read the other articles. Even when you think that you have mastered a problem, you will be astonished to find that there is another interpretation of the problem and will learn something new.
The editorial solution is wrong, we should free up the node(to be deleted) memory before returning from the function.
@PERLANARAYANA Java does garbage collection automatically. But you need to do it manually in C++.
@nrl Usually, yes, deleting a node from a linked list is O(n), but that's because you have to iterate through the list to find what you want to delete. When you're already given a pointer to the node, like here, you don't have to worry about that.
The requirement is not clear because I don't know which node to be removed from the ListNode. It would be clear to show how caller calls this method deleteNode()
I copied every node.val to the one before and set the last one to null. What a shame.
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.