Skip to content

Instantly share code, notes, and snippets.

@yokiy
Created June 27, 2014 01:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yokiy/7da78a4396e307ced78d to your computer and use it in GitHub Desktop.
Save yokiy/7da78a4396e307ced78d to your computer and use it in GitHub Desktop.
cc 2.2
#2.2 Implement an algorithm to find the kth to last element of a singly linked list.
# supose that the length of the link is unknown
from LinkedList import Node, LinkedList
def nthtolast(head, k):
if head is None:
return
p1 = head
p2 = head
for i in range(0, k-1):
if p2 is not None:
p2 =p2.next
while p2.next is not None:
p1 = p1.next
p2 = p2.next
print p1.data
test = LinkedList()
for i in range(15):
test.AddNode(i)
nthtolast(test.head, 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment