Problem 2.2: Implement an algorithm to find the nth to last element of a singly linked list.
The solution on answer page needs only one iteration while other intuitive solution takes more than one iteration.
The solution on answer page needs only one iteration while other intuitive solution takes more than one iteration.
def find_nth_to_last(head, n):
p1 = p2 = head
# Move p2 n nodes forward
for i in range(0, n):
# If p2 runs into the end of list,
# the input is invalid
if p2 == None:
return False
p2 = p2.next
# Move p2 and p1 together until
# p2 runs into the end of list
while True:
if p2 == None:
return p1
p2 = p2.next
p1 = p1.next
I learned that sometimes we can use more than one pointers to achieve a better solution.