leetcode142. 环形链表 II

leetcode142. 环形链表 II

题目

思路

集合法

  • 将节点存入set,若重复出现则说明是环

快慢指针法

  • 分别定义 fast 和 slow 指针,从头结点出发,fast指针每次移动两个节点,slow指针每次移动一个节点,如果 fast 和 slow指针在途中相遇 ,说明这个链表有环。
  • 初次相遇后,将slow设为头结点,slow和fast这两个指针每次只走一个节点, 当这两个指针相遇的时候就是环形入口的节点。

代码

集合法

python 复制代码
class Solution:
    def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        node_set = set()
        current = head
        while current:
            if current in node_set:
                return current
            else:
                node_set.add(current)
                current = current.next
        return None

快慢指针法

python 复制代码
class Solution:
    def detectCycle(self, head: ListNode) -> ListNode:
        slow = head
        fast = head
        
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            
            # If there is a cycle, the slow and fast pointers will eventually meet
            if slow == fast:
                # Move one of the pointers back to the start of the list
                slow = head
                while slow != fast:
                    slow = slow.next
                    fast = fast.next
                return slow
        # If there is no cycle, return None
        return None
相关推荐
Z1Jxxx6 小时前
0和1的个数
数据结构·c++·算法
ldccorpora6 小时前
Chinese News Translation Text Part 1数据集介绍,官网编号LDC2005T06
数据结构·人工智能·python·算法·语音识别
重生之后端学习6 小时前
21. 合并两个有序链表
java·算法·leetcode·链表·职场和发展
AuroraWanderll7 小时前
类和对象(六)--友元、内部类与再次理解类和对象
c语言·数据结构·c++·算法·stl
leaves falling7 小时前
c语言-给定两个数,求这两个数的最大公约数
数据结构·算法
想做后端的小C7 小时前
数据结构:线性表原地逆置
数据结构·考研
jikiecui7 小时前
信奥崔老师:三目运算 (Ternary Operator)
数据结构·c++·算法
无限进步_7 小时前
【C语言&数据结构】另一棵树的子树:递归思维的双重奏
c语言·开发语言·数据结构·c++·算法·github·visual studio
志摩凛7 小时前
Element UI 长表单校验失败后自动展开折叠面板并滚动定位
数据结构·vue.js