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;
    }
}
相关推荐
shehuiyuelaiyuehao14 小时前
算法56,重排链表
数据结构·算法·链表
suhan15 小时前
【数据结构】七、查找:1.查找的概念、线性结构查找(顺序、折半(二分)、插值、稠密、分块、倒排)
数据结构·算法·排序算法
极客 - L U15 小时前
卡尔曼滤波从零到精通
c语言·数据结构·单片机·嵌入式硬件·mcu
Sarvartha18 小时前
栈的四则运算、栈的递归应用
数据结构·算法
YXXY31319 小时前
链表的相关介绍
链表
GG.WinGel20 小时前
三元组中心问题
java·数据结构·算法·青少年编程·蓝桥杯
程序员清风21 小时前
缓存、索引与数据结构的工程选择
数据结构·spring·缓存
爱吃火鸡面呀1 天前
Doris 数据划分实战:List 分区、分桶列与桶数选择
数据结构·list
BK贝壳1 天前
亿级用户签到位图选型复盘:用 bool-hybrid-array 扛冷启动打卡,也把它和 Roaring/Redis 的边界测清楚了
数据结构·python·性能优化·numpy
挖井观天2 天前
《Java数据结构》第一讲:顺序表
数据结构