Created
July 14, 2017 10:07
-
-
Save nopcall/657a4e0b717bd79e9d0ead80c2d3ab22 to your computer and use it in GitHub Desktop.
find entry point of loop linked list
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
#!/bin/env python3 | |
class Node: | |
def __init__(self, data, next=None): | |
self.data = data | |
self.next = next | |
def findEntry(root): | |
fast = slow = root | |
countFast = countSlow = 0 | |
fast = fast.next.next | |
countFast += 2 | |
while fast != slow: | |
fast = fast.next.next | |
countFast += 2 | |
slow = slow.next | |
countSlow += 1 | |
print(countFast, countSlow) | |
fast = root | |
countDistance = 0 | |
while fast != slow: | |
fast = fast.next | |
slow = slow.next | |
countDistance += 1 | |
return countDistance, fast | |
def main(): | |
root = Node(-1) | |
prev = root | |
for i in range(90): | |
cur = Node(i) | |
prev.next = cur | |
prev = cur | |
if i == 47: | |
entry = cur | |
cur.next = entry | |
distance, pos = findEntry(root) | |
print(distance, pos.data) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment