题目

Given a linked list, determine if it has a cycle in it.

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

Example 1:
image.png

  1. Input: head = [3,2,0,-4], pos = 1
  2. Output: true
  3. Explanation: There is a cycle in the linked list, where tail connects to the second node.

Example 2:
image.png

  1. Input: head = [1,2], pos = 0
  2. Output: true
  3. Explanation: There is a cycle in the linked list, where tail connects to the first node.

Example 3:
image.png

  1. Input: head = [1], pos = -1
  2. Output: false
  3. Explanation: There is no cycle in the linked list.

Follow up:

Can you solve it using O(1) (i.e. constant) memory?


题意

判断给定链表中是否存在环。

思路

比较简单的就是将所有遍历到的结点记录下来,如果记录了两次则说明存在环。

0141. Linked List Cycle (E) - 图4#card=math&code=O%281%29)空间的方法是使用快慢指针,慢指针每次走一步,快指针每次走两步,如果快指针追上慢指针则说明存在环。实际上可以看做一个相遇问题,如果快慢指针都在一个环中,且快指针距离慢指针还有n个结点的距离,那么经过n个回合后快指针必定与慢指针重合。


代码实现

Java

Hash

  1. public class Solution {
  2. public boolean hasCycle(ListNode head) {
  3. if (head == null) {
  4. return false;
  5. }
  6. Set<ListNode> set = new HashSet<>();
  7. while (head != null) {
  8. if (!set.add(head)) {
  9. return true;
  10. }
  11. head = head.next;
  12. }
  13. return false;
  14. }
  15. }

快慢指针

  1. public class Solution {
  2. public boolean hasCycle(ListNode head) {
  3. if (head == null) {
  4. return false;
  5. }
  6. ListNode slow = head, fast = head;
  7. while (fast.next != null && fast.next.next != null) {
  8. slow = slow.next;
  9. fast = fast.next.next;
  10. if (fast == slow) {
  11. return true;
  12. }
  13. }
  14. return false;
  15. }
  16. }

JavaScript

  1. /**
  2. * @param {ListNode} head
  3. * @return {boolean}
  4. */
  5. var hasCycle = function (head) {
  6. const nodes = new Set()
  7. while (head) {
  8. if (nodes.has(head)) {
  9. return true
  10. }
  11. nodes.add(head)
  12. head = head.next
  13. }
  14. return false
  15. }