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;
    }
}
相关推荐
岑梓铭2 小时前
《考研408数据结构》第一章复习笔记
数据结构·笔记·考研·408
lifallen3 小时前
Hadoop MapOutputBuffer:Map高性能核心揭秘
java·大数据·数据结构·hadoop·算法·apache
散1123 小时前
01数据结构-B树练习及B+树特点
数据结构·b树
书院门前细致的苹果4 小时前
MySQL 中的 B+树和 B树的区别详解
数据结构·数据库·mysql
半桔5 小时前
【STL源码剖析】二叉世界的平衡:从BST 到 AVL-tree 和 RB-tree 的插入逻辑
java·数据结构·c++·算法·set·map
塔中妖6 小时前
【华为OD】分割数组的最大差值
数据结构·算法·华为od
凯子坚持 c6 小时前
Redis 核心数据结构:String 类型深度解析与 C++ 实战
数据结构·c++·redis
songx_997 小时前
leetcode29( 有效的括号)
java·数据结构·算法·leetcode
爱编程的化学家13 小时前
代码随想录算法训练营第六天 - 哈希表2 || 454.四数相加II / 383.赎金信 / 15.三数之和 / 18.四数之和
数据结构·c++·算法·leetcode·双指针·哈希