142. Linked List Cycle II

142. Linked List Cycle II

題目

給出一個鏈表,如果成環,則返回環開始的結點;如果不成環,返回null。

代碼塊

/**
 * 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 fastNode = head.next;
        ListNode slowNode = head;
        while(fastNode != null && fastNode.next != null){
            if(fastNode == slowNode){
                int len = 1;
                fastNode = fastNode.next;
                while(fastNode != slowNode){
                    len++;
                    fastNode = fastNode.next;
                }
                fastNode = head;
                slowNode = head;
                for(int i = 0; i < len; i++){
                    fastNode = fastNode.next;
                }
                while(fastNode != slowNode){
                    fastNode = fastNode.next;
                    slowNode = slowNode.next;
                }
                return fastNode;
            }
            fastNode = fastNode.next.next;
            slowNode = slowNode.next;
        }
        return null;
    }
}

代碼分析

本題是上個題目(141.Linked List Cycle I)的拓展。根據劍指offer的描述,思路如下:
第一:判斷是否成環,如果是,就進行第二步,否則,返回null。<這是個大框架。就是141的結構>
第二:計算出環的長度CycleLength;
第三:讓fastNode 和 slowNode從頭開始。並讓fastNode先走CylceLength步;
第四:然後讓fastNode 和 slowNode 同時前進,直到二者相遇,返回此時的結點即可。

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