LeetCode 142. 環形鏈表 II

142. 環形鏈表 II

題目

給定一個鏈表,返回鏈表開始入環的第一個節點。 如果鏈表無環,則返回 null。

說明:不允許修改給定的鏈表。

進階:

你是否可以不用額外空間解決此題?

思路

1)採用 hashset ,返回第一個重複出現的節點

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) {
              if (head == null || head.next ==null)
            return null;

        ListNode slowIndex = head;
        ListNode fastIndex = head;

        while (fastIndex != null && fastIndex.next != null){
            slowIndex =slowIndex.next;
            fastIndex =fastIndex.next.next;

            if (slowIndex == fastIndex){
                slowIndex = head;

                while (slowIndex != fastIndex){
                    slowIndex = slowIndex.next;
                    fastIndex =fastIndex.next;
                }
                return slowIndex;
            }
        }
        return null;  
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章