leetcode142.环形链表II

思路源自代码随想录,通过快慢指针解决

java 复制代码
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                ListNode index1 = head;
                ListNode index2 = fast;
                while (index1 != index2) {
                    index1 = index1.next;
                    index2 = index2.next;
                }
                return index1;
            }
        }
        return null;
    }
}
相关推荐
梅梅绵绵冰1 天前
算法题-矩阵
数据结构·算法·矩阵
奋发向前wcx1 天前
y1,y2总复习笔记5 2026.7.19
数据结构·笔记·算法
ChaoZiLL2 天前
我的数据结构4-栈和队列
数据结构
miller-tsunami2 天前
顺序表相关知识点
数据结构·顺序表
华玥作者2 天前
uniapp 万条数据不卡顿:我写了个虚拟列表组件 hy-list,原生支持瀑布流
数据结构·uni-app·list·vue3
2401_841495642 天前
【数据结构】B*树
数据结构·c++·b树·算法·删除·插入·三分分裂
晚笙coding2 天前
LeetCode 108:将有序数组转换为二叉搜索树 —— 从数组到平衡二叉树的递归构造
数据结构·算法·leetcode
不如语冰2 天前
AI大模型入门-模块导入import
数据结构·人工智能·pytorch·python
岑梓铭2 天前
《考研408数据结构》第七章(7.1 查找:顺序查找、折半查找、分块查找)复习笔记
数据结构·笔记·考研·408·ds·查找
壹号用户2 天前
c++入门之list了解及使用
数据结构·list