python3题解 -快慢指针| #链表中环的入口结点#

链表中环的入口结点

https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def EntryNodeOfLoop(self, pHead:ListNode):
        # write code here
        slow = self.hasCycle(pHead)
        if not slow: return None
        fast = pHead
        while fast !=slow:
            slow = slow.next
            fast = fast.next
        return slow

    def hasCycle(self, head):
        if not head:return None
        fast = head
        slow = head
        while fast != None and fast.next != None:
            fast = fast.next.next
            slow = slow.next
            if fast == slow:
                return slow
        return None
# class Solution:
#     # 判断有没有环,返回相遇的地方
#     def EntryNodeOfLoop(self, pHead: ListNode):
#         slow = self.hasCycle(pHead)
#         # 没有环
#         if slow == None:
#             return None
#         # 快指针回到表头
#         fast = pHead
#         # 再次相遇即是环入口
#         while fast != slow:
#             fast = fast.next
#             slow = slow.next
#         return slow

#     def hasCycle(self, head):
#         # 先判断链表为空的情况
#         if head == None:
#             return None
#         # 快慢双指针
#         fast = head
#         slow = head
#         # 如果没环快指针会先到链表尾
#         while fast != None and fast.next != None:
#             # 快指针移动两步
#             fast = fast.next.next
#             # 慢指针移动一步
#             slow = slow.next
#             # 相遇则有环
#             if fast == slow:
#                 # 返回相遇的地方
#                 return slow
#         # 到末尾则没有环
#         return None

全部评论

相关推荐

昨天 15:52
东南大学 C++
点赞 评论 收藏
分享
我就是0offer糕手:北大不乱杀
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务