Skip to content

Latest commit

 

History

History
40 lines (33 loc) · 886 Bytes

141.linked-list-cycle.md

File metadata and controls

40 lines (33 loc) · 886 Bytes

借助 hash 表

var hasCycle = function (head) {
  let dataMap = new Set();
  while (head) {
    if (dataMap.has(head)) {
      return true;
    }
    dataMap.add(head);
    head = head.next;
  }
  return false;
};

快慢指针

快指针每次移动两步,慢指针每次移动一步

如果存在环,快指针与慢指针就会相遇,否则快指针会到达链表结尾

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