In this post, we will discuss a method to delete the kth element from the end of the linked list. In order to delete the required node, we first need to find the kth element from the end of the linked list and then we can delete that element, so in one of the previous posts we have discussed a method to find kth element from the end of the linked list and In another post we have seen a method to delete node from linked list with the only pointer to that node, So combining the 2 methods we can delete the kth element from the end of the linked list.
Have a look at the below posts for an explanation of the methods used in this post
Have a look at the below posts for an explanation of the methods used in this post
- Finding kth element from the end of the Linked list
- Deleting element from the Linked List with only pointer to that node
- Initialize 2 pointers first and second to head node
- Move node first to the kth node from the start
- Move both first and second node through the list till the first node reaches the last node
- At this point, the second node points to the kth node from the end
- Delete the second node using delete method.
We use the same algorithm that we used in our earlier post to delete the node. But this time we will pass the pointer that points to the kth element from the end to the method.
Let look at the code.
C++ Program
Sample input and output to check the program
You might also be interested in
Comments
Post a Comment