IT相关北美程序员面试干货

LeetCode 141 [Linked List Cycle]

2016-06-07  本文已影响88人  Jason_Yuan

原题

给定一个链表,判断它是否有环。

样例
给出 -21->10->4->5, tail connects to node index 1,返回 true

解题思路

完整代码

# 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
        """
        slow, fast = head, head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                return True
        return False
上一篇 下一篇

猜你喜欢

热点阅读