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;
}
Can't you delete the last element by just setting it to null ?
ReplyDeleteYes, you can - thanks Dhaval :)
DeleteHey,
DeleteSorry 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.
This comment has been removed by the author.
ReplyDelete