Easy question, Easy solution(JAVA)


  • 24
    public class Solution {
        public void deleteNode(ListNode node) {
            if(node != null && node.next != null) {
                node.val = node.next.val;
                node.next = node.next.next;
            }
        }
    }

  • -11
    P

    Great!
    But how about if the node is the last one?
    I think there needs
    "
    if (node.next == null)
    {
    node = null;
    }
    "


  • 0

    The question given a condition that delete node except the tail.


  • 0
    H

    You cannot set node null in this function actually, because it is a local variable.


  • 0
    S

    if(node != null && node.next != null), the answer with this condition.


  • 3
    W

    Given the condition that the node to be deleted won't be the tail one, above solution can be simplified to :

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

  • 0
    J

    Can someone explain why a loop isn't needed to iterate through the List node and a simple if statement will suffice?


Log in to reply
 

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