解法一:哈希表
思路同141. 环形链表解法一。
/**
* 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) {
Set<ListNode> set = new HashSet<>();
while (head != null) {
if (set.contains(head)) {
return head;
}
set.add(head);
head = head.next;
}
return null;
}
}
解法二:快慢指针
思路同141. 环形链表解法二,但是判断有环后找出环的起始结点还需要进一步处理。通过简单数学计算可以发现从链表头出发,和慢指针以相同的步长移动会在环的起始结点相遇。
/**
* 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 p1 = head;
ListNode p2 = head;
while ((p1 != null) && (p2 != null)) {
p1 = p1.next;
if (p1 != null) {
p1 = p1.next;
} else {
break;
}
p2 = p2.next;
if (p1 == p2) {
ListNode ans = head;
while (ans != p2) {
ans = ans.next;
p2 = p2.next;
}
return ans;
}
}
return null;
}
}