Created
December 20, 2018 17:23
-
-
Save pepasflo/5386d30581712632dbb38a952771c65f to your computer and use it in GitHub Desktop.
Programming puzzle: Does this linked list have a loop? https://www.interviewcake.com/question/python/linked-list-cycles?__s=rf71cpqpqpezb7dgts5r
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
#!/usr/bin/env python | |
# does this linked list have a cycle? | |
# https://www.interviewcake.com/question/python/linked-list-cycles?__s=rf71cpqpqpezb7dgts5r | |
class ListNode: | |
next = None | |
def has_loop(l): | |
seen = set() | |
current = l | |
while True: | |
if current is None: | |
# reached the end: no loop. | |
return False | |
if current in seen: | |
# found a loop | |
return True | |
seen.add(current) | |
current = current.next | |
# the list is not a loop | |
def testcase0(): | |
head = ListNode() | |
head.next = ListNode() | |
return head | |
# the list is an end-to-end loop | |
def testcase1(): | |
head = ListNode() | |
head.next = ListNode() | |
head.next.next = head | |
return head | |
# the list loops back into the middle | |
def testcase2(): | |
head = ListNode() | |
head.next = ListNode() | |
head.next.next = ListNode() | |
head.next.next.next = head.next | |
return head | |
if __name__ == "__main__": | |
tests = { | |
testcase0(): False, | |
testcase1(): True, | |
testcase2(): True | |
} | |
for testcase, expected in tests.iteritems(): | |
assert has_loop(testcase) == expected | |
print "all tests passed." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment