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;
    }
}
相关推荐
xlq2232214 小时前
12.排序(上)
数据结构·算法·排序算法
Miraitowa_cheems16 小时前
LeetCode算法日记 - Day 59: 字母大小写全排列、优美的排列
java·数据结构·算法·leetcode·决策树·职场和发展·深度优先
岑梓铭16 小时前
《考研408数据结构》第三章(3.1 栈)复习笔记
数据结构·笔记·考研·408
Zzzzmo_18 小时前
Java数据结构:ArrayList与顺序表2
java·数据结构
Jiezcode19 小时前
LeetCode 148.排序链表
数据结构·c++·算法·leetcode·链表
nsjqj21 小时前
数据结构:Map 和 Set (二)
java·开发语言·数据结构
YouEmbedded1 天前
解码数据结构内核链表
数据结构·链表·内核链表
Han.miracle1 天前
数据结构——二叉树学习
数据结构·学习
hello_lain1 天前
9.1 简单排序(冒泡、插入)(排序(上))
c语言·数据结构·算法·排序算法