AcWing 34. 链表中环的入口结点
原题链接
中等
作者:
buchiyu
,
2021-05-14 11:18:18
,
所有人可见
,
阅读 213
节点对比
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def entryNodeOfLoop(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
p = slow = fast = head
while slow and fast:
if not fast.next: return None
slow = slow.next
fast = fast.next.next
if slow == fast:
slow = head
while slow != fast:
slow = slow.next
fast = fast.next
return slow
return None
对比节点值
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def entryNodeOfLoop(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
p = slow = fast = head
while slow and fast:
if not (fast.next and fast.next.next): return None
slow = slow.next
fast = fast.next.next
if slow.val == fast.val:
slow = head
while slow.val != fast.val:
slow = slow.next
fast = fast.next
return slow
return None