题目描述:给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
思路一:利用 Set结构存储已经遍历过的节点, 可以获得O(n)的时间复杂度,但是可会有比较高的空间复杂度。
public ListNode EntryNodeOfLoop(ListNode head) {
Set<ListNode> used = new HashSet<>();
while (head!=null) {
if (used.contains(head)) return head;
used.add(head);
head = head.next;
}
return null;
}
思路二: 快慢指针法,快指针一次前进两步,慢指针一次前进一步,技巧性较强。
分析假设快慢指针从头节点出发,头节点到入环节点距离是a,前进s步后二者相遇, 环的长度为c, 快指针比满指针多走了n圈,他们相遇的位置离入环节点距离为x,可以分析如下等式
2s - s = n c
s = a + x + kc = n c
a - (c - x). = (n - k) *c
现在让两个慢指针,一个从头节点出发,一个从相遇点出发,他们下一次相遇的位置的时候,二者的距离差值是环的整数倍,刚好是入环节点。
public class Solution {
ListNode EntryNodeOfLoop(ListNode h){
if(h == null || h.next == null)
return null;
ListNode slow = h;
ListNode fast = h;
while(fast != null && fast.next != null ){
slow = slow.next;
fast = fast.next.next;
if(slow == fast){
ListNode p=h;
ListNode q=slow;//相当于让q指向了m1
while(p != q){
p = p.next;
q = q.next;
}
if(p == q)
return q;
}
}
return null;
}
时间复杂度:O(N), 空间O(1)