力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
使用hash实现:
public ListNode hasCycle(ListNode head) {
ListNode pos = head;
HashSet<ListNode> listNodes = new HashSet<>();
while (pos != null) {
if (listNodes.contains(pos)) {
return pos;
} else {
listNodes.add(pos);
}
pos = pos.next;
}
return null;
}
快慢指针实现:
public ListNode detectCycle(ListNode head) {
//定义快慢指针
ListNode fast = head, slow = head;
while (fast != null) {
if (fast.next != null) {
//快指针走2步,慢指针走一步
fast = fast.next.next;
slow = slow.next;
} else {
return null;
}
//2个指针相遇,让快指针指向头部,2个指针每一次走相同步数
// 最后后面的指针会指向环节点
if (fast == slow) {
ListNode temp = head;
while (temp != slow) {
temp = temp.next;
slow = slow.next;
}
return temp;
}
}
return null;
}