题目大意:给一个链表,判断是否有环,若没有,则返回null;否则返回环的起始节点。
这题可以有两种解决办法,一种使用额外空间,另一种则不开辟额外空间。
解法一:使用额外空间
选择Java的HashSet,HashSet底层是通过HashMap实现的。当扫描到一个已经存在的节点时,这个节点就是环的起始点。空间复杂度和时间复杂度都是O(n)。
/**
* 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;
HashSet<ListNode> set = new HashSet<ListNode>();
ListNode p = head;
while(p != null) {
if(set.contains(p) == true) return p;
set.add(p);
p = p.next;
}
return null;
}
}
解法二:不使用额外空间
两个指针p、q,p指针每次走一步,q指针每次走两步,若存在环,则p与q一定会走到同一个节点,否则q一定先走到链表尾。存在环时,假设p、q现指向同一个节点,设环起始点距链表起始点x,设p走过的步数为y,则q走过的步数为2y,假设链表长度为n。
存在公式:(2y-x)-(y-x) = k(n-x);k为常量。
得出y=k(n-x),当k=1时,p、q所在的节点距离环的起始点为(n-2x),由于环的长度为(n-x),所以p或q再向后走x步就到达环的起始节点位置。
有以下代码:
/**
* 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 p = head, q = head;
while(p.next != null && q.next != null) {
p = p.next;
q = q.next;
if(q.next == null) return null;
q = q.next;
if(p == q) break;
}
if(q.next == null) return null;
p = head;
while(p != q) {
p = p.next;
q = q.next;
}
return p;
}
}