Question: https://oj.leetcode.com/problems/linked-list-cycle/
Question Name: Linked List Cycle
Same as the problem in Cracking the Coding Interview.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param head, a ListNode # @return a boolean def hasCycle(self, head): if head == None: return False slower = head # Move one step each time quicker = head # Move two steps each time while quicker.next != None and quicker.next.next != None: slower = slower.next quicker = quicker.next.next if slower == quicker: return True # quicker reach the end. Limited list never have cycle. return False |