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;
    }
}
相关推荐
老师我太想进步了20261 天前
【数据结构-8】栈的实现
c语言·数据结构·算法
【心态好不摆烂】2 天前
数据结构基础精讲3
数据结构·算法
岑梓铭2 天前
《考研408数据结构》第七章(B树 和 B+树)复习笔记
数据结构·笔记·b树·考研·408
岑梓铭2 天前
《考研408数据结构》第八章(排序)复习笔记
数据结构·笔记
Pniubi3 天前
力扣24. 两两交换链表中的节点(递归)
算法·leetcode·链表
nice_lcj5203 天前
LRU 缓存入门:它是什么、怎么用、面试怎么手写
java·数据结构·缓存·面试·lru
꧁细听勿语情꧂3 天前
直接选择排序,堆排序,冒泡排序,递归快速排序、hoare版本、挖坑法、lomuto前后指针,非递归快速排序
c语言·开发语言·数据结构·算法
Pniubi4 天前
关于算法用现成数据结构和手撕
数据结构
老师我太想进步了20264 天前
【数据结构-6】算法美学之单链表(1)
数据结构·算法
希望我万事顺遂4 天前
力扣hot100-滑动窗口最大值
数据结构·算法·leetcode