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;
    }
}
相关推荐
雪花desu24 分钟前
【Hot100-Java简单】:两数之和 (Two Sum) —— 从暴力枚举到哈希表的思维跃迁
java·数据结构·算法·leetcode·哈希表
2401_8414956440 分钟前
【游戏开发】登山赛车
数据结构·python·游戏·游戏开发·pygame·登山赛车游戏·游戏打包发布
爱吃生蚝的于勒1 小时前
【Linux】深入理解软硬链接
linux·运维·服务器·c语言·数据结构·c++·算法
老王熬夜敲代码1 小时前
C++模版元编程1
数据结构·c++·笔记
客梦1 小时前
数据结构--学生管理系统
数据结构·笔记
小李小李快乐不已1 小时前
动态规划理论基础
数据结构·c++·算法·leetcode·动态规划
im_AMBER1 小时前
数据结构 15 【复习】树和二叉树小结 | 图算法 | 拓扑排序 | AOE 网
数据结构·笔记·学习·算法·图论
太理摆烂哥1 小时前
数据结构之图
数据结构·算法
小李小李快乐不已2 小时前
算法技巧理论基础
数据结构·c++·算法·leetcode·hot100
草莓熊Lotso2 小时前
《算法闯关指南:递归,搜索与回溯算法--递归》--04. 两两交换链表中的结点 ,05.Pow(x,n)
数据结构·算法·链表