首页 > 其他 > 详细

环形链表2

时间:2021-09-21 17:35:16      阅读:19      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

 双指针:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def detectCycle(self, head: ListNode) -> ListNode:
        if head is None or head.next is None:
            return 
        slow = fast = head
        while slow and fast and fast.next :
            slow = slow.next
            fast = fast.next.next
            if slow is fast:
                break
        if fast is None or fast.next is None: #表明没有环
            return 
        tmp = head
        while tmp is not slow:
            tmp = tmp.next
            slow = slow.next
        return slow
 
语言特性:
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def detectCycle(self, head: ListNode) -> ListNode:
#        if head is None and head.next is None:
 #           return head 
        hashmap = []
        while head:
            if head in hashmap:
                return head
            hashmap.append(head)
            head = head.next
        return None

环形链表2

原文:https://www.cnblogs.com/shamoguzhou/p/15306596.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!