环形链表题目

【Leetcode 141】环形链表_结点
【Leetcode 141】环形链表_链表_02
【Leetcode 141】环形链表_链表_03

public boolean hasCycle(ListNode head) {
Set<ListNode> nodesSeen = new HashSet<>();
while (head != null) {
if (nodesSeen.contains(head)) {
return true;
} else {
nodesSeen.add(head);
}
head = head.next;
}
return false;
}

【Leetcode 141】环形链表_.net_04
【Leetcode 141】环形链表_.net_05

public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while (slow != fast) {
if (fast == null || fast.next == null) {
return false;
}
slow = slow.next;
fast = fast.next.next;
}
return true;
}

【Leetcode 141】环形链表_结点_06
参考链接
​​​ https://leetcode-cn.com/problems/linked-list-cycle/solution/huan-xing-lian-biao-by-leetcode/​

扩展拿到环的入口结点
​​​ https://zhuanlan.zhihu.com/p/103626709​