Finding the nth to last node in a linked list

2017-10-17 20:08:34

I have a linked list with n elements and my goal is to find the 'nth to last element' in the list. I would like to present my approach. Please provide your opinions on whether it is optimal or how may I improve it.

Sample linked list "4->5->6->8->2->9->1"

Suppose the question indicates find 3th to last element in the list.

a)In a single pass, get the length of the linked list

b) Determine which node needs to be traversed upto (len(list)-nth element from last-1)

c) Make (len(list)-nth element from last-1) moves from head to get the element

Run time should be O(n)

Thank you