Problem link:
http://oj.leetcode.com/problems/linked-list-cycle/
We set two pointers: the faster pointer goes two steps each iteration, and the slower one goes one step.
If the two pointers meet some time, it follows that there is a loop; otherwise, the faster pointer will touch the end of the singly linked list, and return False.
The algorithm will solve the problem correctly and terminate in linear time. For details, please refere to my homepage doc.
The python code is as follows.
# 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):
slow = head
fast = head
while fast is not None:
slow = slow.next
if fast.next is None:
break
else:
fast = fast.next.next
if slow == fast:
return True
return False
浙公网安备 33010602011771号