leetcode:142. Linked List Cycle II(Java)解答

时间:2022-12-25 19:34:59

转载请注明出处:z_zhaojun的博客
原文地址:http://blog.csdn.net/u012975705/article/details/50412899
题目地址:https://leetcode.com/problems/linked-list-cycle-ii/

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?

解法(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) {
        if (head == null || head.next ==null) {
            return null;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        while (slow != null && fast != null && slow != fast) {
            // if (slow == fast) {
            // temp = slow;
            // break;
            // }
            slow = slow.next;
            fast = fast.next == null ? fast.next : fast.next.next;
        }
        if (slow == fast) {
            slow = head;
            fast = fast.next;
            while (slow != fast) {
                slow = slow.next;
                fast = fast.next;
            }
            return slow;
        }
        return null;
    }
}