141. Linked List Cycle
# 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 head == None or head.next == None:
return False
slow, fast = head, head.next
while fast and fast.next:
if slow == fast:
return True
slow = slow.next
fast = fast.next.next
return False
142. Linked List Cycle II
先判斷是不是有環(huán)动壤;再判斷環(huán)的大小n;快的先走n步淮逻,快慢相等就是入口琼懊。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
node = self.hasCircle(head)
if node == None:
return None
n = self.getLen(node)
slow = fast = head
while n > 0:
fast = fast.next
n -= 1
while slow != fast:
slow = slow.next
fast = fast.next
return slow
def hasCircle(self, head):
if head == None or head.next == None:
return None
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return slow
return None
def getLen(self, head):
p = head.next
n = 1
while p != head:
n += 1
p = p.next
return n