Given A linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Idea: The stupid way is to each node and then open up a property store whether or not to visit, so walk through it can know whether there is a ring. But in order not to add extra space. Ability to set two pointers. One step at a time, and one step at a time, assuming that there is a ring two pointers will meet again. Conversely, it does not.
# Definition for singly-linked list.# class listnode:# def __init__ (self, x): # self.val = x# Self.next = Nonec Lass Solution: # @param head, a listnode # @return a Boolea def hascycle (self, head): if head is none:
return False p1 = head P2 = head while True: If p1.next are not None: p1=p1.next.next p2= P2.next If P1 is None or P2 is none: return False elif P1 = = P2: return True else: return Fa LSE return False
"Leetcode" "Python" Linked List Cycle