06_环形链表
2019-10-31 本文已影响0人
butters001
# 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:
return False
cur1 = cur2 = head
while cur2 and cur2.next:
cur1 = cur1.next
cur2 = cur2.next.next
if cur1 == cur2:
return True
return False
# leetcode 上最优解 思路一样 快慢指针 上下两个while的条件都对
class Solution2(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head is None:
return head
fast = head
slow = head
while fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
if fast.val == slow.val:
return True
return False