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;
    }
}
相关推荐
wm10434 小时前
代码随想录第四天
数据结构·链表
CoderCodingNo5 小时前
【GESP】C++六级考试大纲知识点梳理, (3) 哈夫曼编码与格雷码
开发语言·数据结构·c++
牛马大师兄5 小时前
数据结构复习 | 什么是数据结构?
数据结构
wu_asia6 小时前
方阵对角线元素乘积计算
数据结构·算法
想逃离铁厂的老铁6 小时前
Day43 >> 300.最长递增子序列 + 674. 最长连续递增序列+ 718. 最长重复子数组
数据结构·算法
宵时待雨7 小时前
数据结构(初阶)笔记归纳4:单链表的实现
c语言·开发语言·数据结构·笔记·算法
wm10437 小时前
代码随想录第三天 链表
数据结构·链表
BLSxiaopanlaile7 小时前
关于子集和问题的几种解法
数据结构·算法·剪枝·回溯·分解
じ☆冷颜〃8 小时前
交换代数的解析延拓及在CS的应用
c语言·数据结构·笔记·线性代数·密码学
程序员-King.8 小时前
day136—快慢指针—重排链表(LeetCode-143)
算法·leetcode·链表·快慢指针