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;
    }
}
相关推荐
Queenie_Charlie3 小时前
stars(树状数组)
数据结构·c++·树状数组
静听山水3 小时前
Redis核心数据结构-Set
数据结构·数据库·redis
独好紫罗兰4 小时前
对python的再认识-基于数据结构进行-a005-元组-CRUD
开发语言·数据结构·python
wengqidaifeng4 小时前
数据结构(三)栈和队列(上)栈:计算机世界的“叠叠乐”
c语言·数据结构·数据库·链表
静听山水4 小时前
Redis核心数据结构
数据结构·数据库·redis
im_AMBER4 小时前
Leetcode 115 分割链表 | 随机链表的复制
数据结构·学习·算法·leetcode
数智工坊4 小时前
【数据结构-树与二叉树】4.7 哈夫曼树
数据结构
!!!!8134 小时前
蓝桥备赛Day1
数据结构·算法
七点半7704 小时前
linux应用编程部分
数据结构
静听山水4 小时前
Redis核心数据结构-Hash
数据结构·redis·哈希算法