LeetCode – Delete Node in a Linked List (Java)

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.

Java Solution

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

Is this problem too easy? Or I'm doing it wrong.

Category >> Algorithms >> Interview  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • chintan thakker

    Your code is correct for somewhat different Question i.e remove elements if access to head is given but somewhat duplicated. There is no need to have seperate condition for last node, Change while(curr.next != null) to while(curr!=null). It works perfectly. Also check if Head is null(i.e if the list is empty otherwise curr = head.next; will throw a null pointer exception)

    1st Method:-

    public void deleteNode(ListNode n) {

    if(head ==null){
    System.out.println("List is Empty");
    }
    if(head.val == n){ //Check if the first node is the one to be deleted
    head=head.next;
    }
    if(head == null){ // Check if there was only one element on Original list
    return;
    }

    ListNode prev = head;
    ListNode curr = head.next;

    while (curr != null){
    if(curr.val == n.val){
    prev.next = curr.next;
    }else{
    prev = prev.next;
    curr = curr.next // no null pointer exception will be shown even if curr.next is null
    }
    }

    }

    2nd method:-


    public void deleteNode(ListNode n) {

    if(head ==null){
    System.out.println("List is Empty");
    }
    if(head.val == n){
    head=head.next;
    }
    if(head == null){ // Check if there was only one element in Original list
    return;
    }
    ListNode curr = head;
    while (curr.next != null) {
    if (curr.next.val == n) {
    curr.next= curr.next.next;
    } else {
    curr = curr.next;
    }
    }
    }

  • Aditya Vutukuri

    You need to take care if this is a head and tail.

    public void deleteNode(ListNode n) {

    node.next = node.next.next;
    }

  • CRH

    This is easy, BUT needs edge cases handling in code/talking to your interviewer. Did you wonder how this will work if the node is the last in the list? 🙂