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;
    }
}
相关推荐
一二学长17 小时前
快速排序(JAVA详细讲解快速排序的四种方式)
数据结构
大数据张老师17 小时前
数据结构——红黑树
数据结构·算法·红黑树
Dream it possible!18 小时前
LeetCode 面试经典 150_链表_两数相加 (57_2_C++_中等)
leetcode·链表·面试
文火冰糖的硅基工坊18 小时前
[人工智能-大模型-54]:模型层技术 - 数据结构+算法 = 程序
数据结构·人工智能·算法
Yupureki18 小时前
从零开始的C++学习生活 13:红黑树全面解析
c语言·数据结构·c++·学习·visual studio
Z...........19 小时前
优选算法(滑动窗口)
数据结构·算法
大数据张老师19 小时前
数据结构——平衡二叉树(2)
数据结构
大数据张老师21 小时前
数据结构——二叉搜索树
数据结构·算法·二叉搜索树·查找·关键路径
.小小陈.1 天前
数据结构3:复杂度
c语言·开发语言·数据结构·笔记·学习·算法·visual studio
立志成为大牛的小牛1 天前
数据结构——二十四、图(王道408)
数据结构·学习·程序人生·考研·算法