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;
    }
}
相关推荐
Jasmine_llq1 小时前
《P3811 【模板】模意义下的乘法逆元》
数据结构·算法·线性求逆元算法·递推求模逆元
虹科网络安全1 小时前
艾体宝干货 | Redis Java 开发系列#2 数据结构
java·数据结构·redis
sin_hielo1 小时前
leetcode 2211
数据结构·算法·leetcode
Queenie_Charlie1 小时前
和为k的连续区间
数据结构·c++·map
爱学java的ptt2 小时前
206反转链表
数据结构·链表
java修仙传2 小时前
力扣hot100:最大子数组和
数据结构·算法·leetcode
hweiyu002 小时前
数据结构:二叉树
数据结构
Rock_yzh2 小时前
LeetCode算法刷题——54. 螺旋矩阵
数据结构·c++·学习·算法·leetcode·职场和发展·矩阵
ベadvance courageouslyミ3 小时前
数据结构(一)
数据结构
lightqjx3 小时前
【C++】对set和map的使用
开发语言·数据结构·c++·stl