142. 環形鏈表2 Leetcode Java

//給定一個鏈表,返回鏈表開始入環的第一個節點。 如果鏈表無環,則返回 null。 
//
// 爲了表示給定鏈表中的環,我們使用整數 pos 來表示鏈表尾連接到鏈表中的位置(索引從 0 開始)。 如果 pos 是 -1,則在該鏈表中沒有環。 
//
// 說明:不允許修改給定的鏈表。 
//
// 
//
// 示例 1: 
//
// 輸入:head = [3,2,0,-4], pos = 1
//輸出:tail connects to node index 1
//解釋:鏈表中有一個環,其尾部連接到第二個節點。
// 
//
// 
//
// 示例 2: 
//
// 輸入:head = [1,2], pos = 0
//輸出:tail connects to node index 0
//解釋:鏈表中有一個環,其尾部連接到第一個節點。
// 
//
// 
//
// 示例 3: 
//
// 輸入:head = [1], pos = -1
//輸出:no cycle
//解釋:鏈表中沒有環。
// 
//
// 
//
// 
//
// 進階: 
//你是否可以不用額外空間解決此題? 
// Related Topics 鏈表 雙指針


//leetcode submit region begin(Prohibit modification and deletion)

/**
 * 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) {

        ListNode fast, slow;
        fast = slow = head;

        //this way cannot judge the one item
      /*  while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow) break;
        }*/
        while (true) {
            if(fast==null||fast.next==null) return null;
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow) break;
        }


        slow = head;
        while (slow != fast) {
            fast = fast.next;
            slow = slow.next;
        }

        return slow;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

 

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