The following function is trying to find the nth
to last element of a singly linked list.
For example:
If the elements are
my approach, what i think is simple and has time complexity O(n).
Step 1: First get the count of number of nodes. Run a for loop starting from first node to the last node
Step 2: Once you have the count, apply simple math, for example if we have find 7th node to the last node and the count of all nodes is 12, then (count - index)- 1 will give some kth node, upto which you will have to traverse and it will be the nth node to the last node. In this case (12 -7)-1 = 4
If the elements are 8->10->5->7->2->1->5->4->10->10 then the result is 7th to last node is 7, which is nothing but 4th node from the beginning.