Created
May 16, 2020 01:43
-
-
Save c02y/ec0042a1ba6b617920b8a52ee2fd45b4 to your computer and use it in GitHub Desktop.
LinkedListCycle.py
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
# 141. Linked List Cycle (Easy) | |
# https://leetcode-cn.com/problems/linked-list-cycle/description/ | |
# Definition for singly-linked list. | |
class ListNode: | |
def __init__(self, x): | |
self.val = x | |
self.next = None | |
class Solution: | |
def __init__(self): | |
self.root = None | |
def addNode(self, root, numbers, index, size): | |
if index < size: | |
temp = ListNode(numbers[index]) | |
root = temp | |
root.next = self.addNode(root.next, numbers, index + 1, size) | |
# the following line make tail point to the head which make root a loop | |
# uncomment it again to see the result | |
# root.next = temp | |
return root | |
def hasCycle(self, head: ListNode) -> bool: | |
one = head | |
two = head | |
while one and two and two.next: | |
one = one.next | |
two = two.next.next | |
if one == two: | |
return True | |
return False | |
if __name__ == '__main__': | |
numbers = [3, 2, 0, -4] | |
solu = Solution() | |
root = solu.addNode(solu, numbers, 0, len(numbers)) | |
print("Loop" if Solution().hasCycle(root) else "Non-loop") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Cpp version: