Skip to content

Instantly share code, notes, and snippets.

@pepasflo
Created December 20, 2018 17:23
Show Gist options
  • Save pepasflo/5386d30581712632dbb38a952771c65f to your computer and use it in GitHub Desktop.
Save pepasflo/5386d30581712632dbb38a952771c65f to your computer and use it in GitHub Desktop.
#!/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