《LeetCode力扣练习》代码随想录——链表(环形链表II—Java)
刷题思路来源于 代码随想录
142. 环形链表 II
-
双指针
/*** 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) {if(head==null){return null;}ListNode slow=head;ListNode fast=head;while(fast.next!=null&&fast.next.next!=null){slow=slow.next;fast=fast.next.next;if(fast==slow){ListNode result=head;while(result!=fast){result=result.next;fast=fast.next;}return result;}}return null;} }