查找列表是否含有環(二)——Leetcode系列(十)

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

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

Proof:

StepOne goes one step each time, StepTwo goes two steps each time. We assume that, there are n steps before entering into the cycle, the cycle length is k, the length between cycle begin's node and meeting node is m, then, we have:

StepOne goes n+xk+m steps, StepTwo goes n + yk+m steps, 2*(n+xk+m) = n + yk + m. So (y-2x)k = n + m;

(y-2x-1)k + (k -m) = n. Thus, we know when StepOne goes from the head, and StepTwo goes from the meeting node, they will meet at the cycle begin.

My Answer:

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

 題目來源:https://oj.leetcode.com/problems/linked-list-cycle-ii/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章