【LeetCode OJ】Linked List Cycle

Posted on 2014-04-04 23:38  卢泽尔  阅读(185)  评论(0)    收藏  举报

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