Skip to content

Instantly share code, notes, and snippets.

@JRJurman
Last active January 3, 2016 23:09
Show Gist options
  • Select an option

  • Save JRJurman/8533265 to your computer and use it in GitHub Desktop.

Select an option

Save JRJurman/8533265 to your computer and use it in GitHub Desktop.
Implement an algorithm to find the nth to last element of a singly linked list
"""
Implement an algorithm to find the nth to last element of a singly linked list
"""
# Assumes that list is at least n elements long
def solve(lnkList, index):
nex = ".nextNode"*(index+1) # index=2 => nex = .nextNode.nextNode.nextNode
cNode = lnkList.head
while (eval("cNode"+nex)!=None): # eval "cNode.nextNode.nextNode.nextNode"
cNode = cNode.nextNode
return cNode
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment