Solution in Java in 2 lines


  • 11
    P

    The idea is to copy the data of next node to current node and then delete the next node.

    public class Solution {
        public void deleteNode(ListNode node) {
            
            node.val = node.next.val;
            node.next = node.next.next;
        }
    }

  • 0
    J

    Good point! Thanks.


  • 0
    H

    thanks, it helps me to understand the reason of this operation


  • 0

    The code needs to check condition,

    public void DeleteNode(ListNode node) {
    
        if (node != null && node.next != null) {
            node.val = node.next.val;
            node.next = node.next.next;
        }            
    }

  • 0
    R

    (node.next != null) is enough to check whether the node is tail or not, why we need also check (node != null). Look forward for reply, thanks!!


Log in to reply
 

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