Created
June 29, 2014 00:00
-
-
Save yokiy/da71157d9de7dc6491ba to your computer and use it in GitHub Desktop.
cc 2.6
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.6 Given a circular linked list, implement an algorithm which returns the node at the beginning of the loop. | |
#slower and faster pointers | |
from LinkedList import Node, LinkedList | |
def findloop(ls): | |
p1 = ls.head | |
p2 = ls.head | |
if p2 is None or p2.next is None: | |
return null | |
while p2.next is not None: | |
p1 = p1.next | |
p2 = p2.next.next | |
if p1 == p2: | |
break | |
p1 = ls.head | |
while p1 != p2: | |
p1 = p1.next | |
p2 = p2.next | |
print 'the loop starts at', p2.data | |
return p2 | |
#test | |
ls = LinkedList() | |
for i in range(10): | |
ls.AddNode(i) | |
start = Node(80) | |
start.next = ls.head.next | |
ls.head.next = start | |
ls.end.next = start | |
findloop(ls) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment