美文网首页
快慢指针 02

快慢指针 02

作者: 眼若繁星丶 | 来源:发表于2020-10-10 19:40 被阅读0次

    快慢指针 02


    LeetCode 142

    https://leetcode-cn.com/problems/linked-list-cycle-ii/

    题解

    https://leetcode-cn.com/problems/linked-list-cycle-ii/solution/142-huan-xing-lian-biao-ii-jian-hua-gong-shi-jia-2/

    /**
     * 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, fast = head;
            while (fast != null && fast.next != null) {
                slow = slow.next;
                fast = fast.next.next;
                // 有环,开始找环的入口
                if (slow == fast) {
                    while (slow != head) {
                        head = head.next;
                        slow = slow.next;
                    }
                    return slow;
                }
                
            }
            return null;
        }
    }
    

    相关文章

      网友评论

          本文标题:快慢指针 02

          本文链接:https://www.haomeiwen.com/subject/mjbjpktx.html