Delete a node given a index in Linked List
Here we will delete a node from the list given the node data to be deleted.
We will maintain two links here so as to link the previous node's next to the deleted node's next.

In the above diagram node to be deleted is 99, so we will link node 12 next to node 37 whose link we can have from node 99 next.
Below is a Java code.
Here we will delete a node from the list given the node data to be deleted.
We will maintain two links here so as to link the previous node's next to the deleted node's next.
In the above diagram node to be deleted is 99, so we will link node 12 next to node 37 whose link we can have from node 99 next.
Below is a Java code.
private void deleteNode(LinkedNode node2) { if(head == null){ System.out.println("List is empty"); return; } if(head.value == node2.value){ head = head.next; return; }else{ LinkedNode temp1 = head; LinkedNode temp = head.next; while(temp != null && temp.value != node2.value ){ temp1 = temp; temp = temp.next; } if(temp == null){ System.out.println("The node to be delete is not found "); }else{ temp1.next = temp.next; } } }Node temp is the node to be deleted and node temp1 points to the previous node to be deleted. Hope you like it. Please comment on doubts.
Happy Learning !!!
0 comments :
Post a Comment