google-code-prettify

Sunday 27 January 2013

Delete node in LinkedList

Delete a given node in a singly linked list. You don't have an access to the root node of the list. You have only access to the given node. Let's suppose this is your definition of a node.
class Node {
    Node next;
    int data;
}
Deleting a node in the middle of a singly linked list could happen if you copy the value from the next node over the given node and then to delete the next node.
public static void deleteMiddleNode(Node n){
    if(n == null){
        System.out.println("Node value is incorrect");
    }
    // in case of last element
    if(n.next == null){
        n = null;
    }
  
    Node next = n.next;
    n.data = next.data;
    n.next = next.next;
}

4 comments:

  1. Can't you delete the last element by just setting it to null ?

    ReplyDelete
    Replies
    1. Yes, you can - thanks Dhaval :)

      Delete
    2. Hey,

      Sorry for the confusion but I think we can't delete last element.

      In Java we use pass by value. So in your code Node n is pointing to the last element.
      Now if we do n=null then we are setting n to null not the last elements in the list which is still not null.

      Hope it makes sense and again sorry for the wrong comment.

      Delete
  2. This comment has been removed by the author.

    ReplyDelete