Created
June 27, 2014 01:44
-
-
Save yokiy/7da78a4396e307ced78d to your computer and use it in GitHub Desktop.
cc 2.2
This file contains 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
#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