List Cycle

题目描述

Given a linked list, determine if it has a cycle in it.

Follow up:

Can you solve it without using extra space?

解题方法

快慢指针two pointer, 注意点是快指针在前每次移动两个,所以只要判断p2 and p2.next存在就可以继续loop

Solution

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if not head or not head.next:
            return False
        p1 = head
        p2 = head
        while p2 and p2.next:
            p1 = p1.next
            p2 = p2.next.next
            if p1 == p2:
                return True

        return False

Reference