Simple Java Solution and Corner Cases


  • 3
    H
    public class Solution {
        public void deleteNode(ListNode node) {
            if (node == null || node.next == null) {
                return;
            }
            node.val = node.next.val;
            node.next = node.next.next;
        }
    }

  • 0
    R

    It is redundant to have node.next == null, which implies that node is tail. You simply can NOT delete a tail without the reference of the previous node.


  • 0
    U

    I think it's the 'node.next == null' check is fine. This way, if the user tries to delete the tail by accident, we would just ignore it instead of throwing a null pointer exception.

    Of course, if this was actual production code, it might be clearer to throw an IllegalArgumentException if the user did try to delete the tail so we wouldn't fail silently.


Log in to reply
 

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