[LeetCode] 142. 环形链表 II

·  阅读 66

Description

Linked List Two Pointers


Python

# 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:
        # double pointers
        f, l = head, head
        # first encounter
        while True:
            if not f or not f.next: return None
            f, l = f.next.next, l.next
            if f == l: break
        # second encounter
        f = head
        while f != l:
            f, l = f.next, l.next
        return f
复制代码

END

分类:
代码人生
标签:
收藏成功!
已添加到「」, 点击更改