leetcode142. Linked List Cycle II

来源:互联网 发布:算法交易是量化 编辑:程序博客网 时间:2024/04/30 08:42

142. Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

Follow up:
Can you solve it without using extra space?

解法

快慢指针判断是否有环,有环的话,将其中一个指针等于head,从头开始一步一步走,直到再次重合,即为所求的点。

/** * 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 || head.next == null) {            return null;        }        ListNode slow = head;        ListNode fast = head.next;        while (slow != fast) {            if (fast == null || fast.next == null) {                return null;            }            slow = slow.next;            fast = fast.next.next;        }        slow = head;        while (slow != fast.next) {            slow = slow.next;            fast = fast.next;        }        return slow;    }}

这里写图片描述

0 0
原创粉丝点击