Delete a node in a singly Linked List having access to that node
  • node
  • singlylinkedlist
  • linkedlist
  • stackqueuelinkedlist
  • delete
  •   
  • Posted: 5 years ago
  • Edit
  • answers (1)
  • views (2956)

Write an algorithm to delete a node in a singly Linked List with access to that node only.


Posted Answers

Since we have only access to the node to be deleted (let's call it current node) and this is a singly Linked List, the pointer to the previous node of the current node is not available. The below algorithm is not applicable if the current node is the last node of the Linked List. The algorithm works as :


  • Copy the data from the next node to the current node.
  • Keep the pointer of the next of the next node of the current node in a temporary variable.
  • Delete the next node of the current node.



public static boolean deleteNodeInASinglyLL(Node node){

/* Error condition check */
/* If the node is null or the last node of the LL */
if(node == null || node.next == null)
return false;

/* Copy the data from the next node to the current node */
node.data = node.next.data;

/* Copy the next of the next node of the current node in a temporary
variable */
Node tempNode = node.next.next;
/* Delete the next node of the current node. */
delete(node.next);
/* Pointer reset - link the current node */
node.next = tempNode;
}

You need to Sign In to post your solution.