美文网首页
141. &142 Linked List Cycle

141. &142 Linked List Cycle

作者: Jonddy | 来源:发表于2018-03-06 08:43 被阅读0次
题目要求:

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

解题思路:
  • 快慢指针 : fast指针一个循环走两步,slow指针一个循环走一步。
  • 示意图
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None


class Solution(object):
    def hasCycle(self, head):
        meet = None
        fast = head
        slow = head

        while fast:
            fast = fast.next
            slow = slow.next
            if fast:
                fast = fast.next
            if fast == slow:
                meet = fast
                break
        if meet == None:
            return False
        else:
            return True


if __name__ == "__main__":
    head, head.next, head.next.next = ListNode(1), ListNode(2), ListNode(3)
    head.next.next.next, head.next.next.next.next = ListNode(3), ListNode(4)
    head.next.next.next.next.next, head.next.next.next.next.next.next = ListNode(4), ListNode(5)
    head.next.next.next.next.next.next.next = head.next.next

    print(Solution().hasCycle(head))

相关文章

网友评论

      本文标题:141. &142 Linked List Cycle

      本文链接:https://www.haomeiwen.com/subject/embhfftx.html