142. 環形鏈表 II
阿新 • • 發佈:2019-05-11
tco 代碼 else lee 是否 連接 conn 沒有 解決
題目描述
給定一個鏈表,返回鏈表開始入環的第一個節點。 如果鏈表無環,則返回 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
解釋:鏈表中沒有環。
進階:
你是否可以不用額外空間解決此題?
分析
快慢指針,判斷是否有環,如果有環,則遍歷出現第一次環在輸出,否則輸出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) { boolean hasCycle = false; if(head == null || head.next == null){ return null; } ListNode slow = head; ListNode fast = head; while(fast != null && fast.next != null){ slow = slow.next; fast = fast.next.next; if(slow == fast){ hasCycle = true; break; } } if(hasCycle){ ListNode q = head; while(q != slow){ slow = slow.next; q = q.next; } return q; }else{ return null; } } }
142. 環形鏈表 II