Last active
January 3, 2016 23:09
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| 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