Remove Nth Node from Linked List
Remove 3rd node from below list
Input
Anbu -> Arul -> Arasu-> Bharath-> Catherine -> Davidson
Output
Anbu -> Arul -> Bharath-> Catherine -> Davidson
Idea: Traverse to the Kth Position and point the reference of temp to one next to it. We need to handle one edge case which is when the Kth position is first node then in such case the head should be changed to point temp next position.
public class RemoveNthNodeFromLL {
public static void main(String[] args) {
SimpleLinkedList simpleLinkedList = new SimpleLinkedList();
simpleLinkedList.insertNodeAtEnd("Anbu");
simpleLinkedList.insertNodeAtEnd("Arul");
simpleLinkedList.insertNodeAtEnd("Arasu");
simpleLinkedList.insertNodeAtEnd("Bharath");
simpleLinkedList.insertNodeAtEnd("Catherine");
simpleLinkedList.insertNodeAtEnd("Davidson");
simpleLinkedList.printLinkedList();
System.out.println("--------------After Removing 3rd Node--------------");
removeNthNode(simpleLinkedList, 3);
simpleLinkedList.printLinkedList();
}
public static void removeNthNode(SimpleLinkedList simpleLinkedList, Integer indexOfNodeToBeRemoved){
Node temp = simpleLinkedList.head;
//Edgecase1 : If Kth index is 1
if(indexOfNodeToBeRemoved == 1){
simpleLinkedList.head = temp.next;
return;
}
for(int idx=1;idx<indexOfNodeToBeRemoved-1;idx++){
temp = temp.next;
}
temp.next = temp.next.next;
}
}
Output
Anbu Arul Arasu Bharath Catherine Davidson --------------After Removing 3rd Node-------------- Anbu Arul Bharath Catherine Davidson