【Golang】LeetCode 142. 环状链表 II

142. 环状链表 II

题目描述

思路

「141. 环形链表」本质上是这道题目的简化,因此我们就跳过 Hot 100 当中的这道题目,直接来将「142. 环形链表 II」。

想要找到环形链表的入口,我们需要记住一个结论,那就是当我们首先通过快慢指针找到环形链表当中的相交点时,令slow, fast := head, intersectionintersection是相交点),然后同时令它们不断地后移一个节点,最终它们相遇的位置,就是环的入口。

基于以上思路,我们来写代码解决这道题。

Golang 题解

go 复制代码
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func detectCycle(head *ListNode) *ListNode {
    slow, fast := head, head
    for fast != nil {
        slow = slow.Next
        fast = fast.Next
        if fast != nil {
            fast = fast.Next
        }
        if slow == fast {
            break
        }
    }

    fast = head
    for slow != fast && slow != nil {
        slow, fast = slow.Next, fast.Next
    }

    return slow
}
相关推荐
hold?fish:palm10 小时前
34 合并K个升序链表
javascript·算法·链表
Navigator_Z12 小时前
LeetCode //C - 1252. Cells with Odd Values in a Matrix
c语言·算法·leetcode
语戚14 小时前
力扣 1621. 大小为K的不重叠线段的数目:动态规划(Java 实现)
java·算法·leetcode·动态规划·力扣·dp
青山木14 小时前
Hot 100 --- 最长有效括号
java·数据结构·算法·leetcode·动态规划
这料鬼有毒15 小时前
二刷hot100-1143.最长公共子序列
算法·leetcode·动态规划
chenqianghqu21 小时前
go语言SDK升级到1.27更新调试
golang
无敌贵点大王21 小时前
RTThread学习记录10——C语言实现面向对象的编程
c语言·stm32·学习·链表
Nil20821 小时前
leetcode 394字符串解码
leetcode
ttwuai1 天前
Go开源后台管理系统推荐:怎么先排除 Fork、镜像和同名项目?
golang
一起努力啊~1 天前
算法题打卡力扣第1658题:将 x 减到 0 的最小操作数(mid)
学习·leetcode