Q.) Implement an algorithm to delete a node in the middle of a single linked list, given  only access to that node

ans.)

The solution to this is to simply copy the data from the next node into this node and then
delete the next node

NOTE: This  problem  can  not  be  solved  if  the  node  to  be  deleted  is  the  last  node
in the linked list  That’s ok—your interviewer wants to see you point that out  You
could consider marking it as dummy in that case   This is an issue you should dis-
cuss with your interviewer

public static boolean deleteNode(LinkedListNode n) {
  if (n == null || n.next == null) {
    return false; // Failure
  } 
  LinkedListNode next = n.next; 
  n.data = next.data; 
  n.next = next.next; 
  return true;
}
Tagged with:  

Leave a Reply

Free WordPress Theme
Free WordPress Theme