/**
* 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) {
HashSet<ListNode> hashSet = new HashSet<ListNode>();
while (head != null) {
if (hashSet.contains(head))
return head;
hashSet.add(head);
head = head.next;
}
return null;
}
}
HashSet不多说了,无脑解决。
/**
* 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) {
return null;
}
ListNode slowNode = head, fastNode = head;
boolean n = false;
while (fastNode.next != null && fastNode.next.next != null) {
slowNode = slowNode.next;
fastNode = fastNode.next.next;
if (slowNode == fastNode) {
n = true;
break;
}
}
if (n) {
slowNode = head;
while (slowNode != fastNode) {
fastNode = fastNode.next;
slowNode = slowNode.next;
}
return slowNode;
}
return null;
}
}
第二种方法看看该视频,这种方法没必要列出具体的数学推导,从现有例子中总结出一种可行的方法,找不出反例即可直接用。