判断节点有无环路

  1. class ListNode {
  2. val: number;
  3. next: ListNode | null;
  4. constructor(val?: number, next?: ListNode | null) {
  5. this.val = val === undefined ? 0 : val;
  6. this.next = next === undefined ? null : next;
  7. }
  8. }
  9. function hasCycle(head: ListNode | null): boolean {
  10. let slow = head;
  11. let fast = slow;
  12. /*
  13. 快慢指针必然相遇, 但相遇点不一定是入环的点。
  14. */
  15. while (fast !== null && fast.next !== null) { // 必要条件
  16. slow = slow!.next;
  17. fast = fast.next.next;
  18. if (slow === fast) {
  19. return true;
  20. }
  21. }
  22. return false;
  23. }
  • hashmap

    1. function hasCycle1(head: ListNode | null): boolean {
    2. let hashmap: Map<ListNode, boolean> = new Map();
    3. while (head && head.next) {
    4. if (hashmap.has(head.next)) {
    5. //head.next 已经在hashpmap 中, 那么这个next必然是入环点
    6. return true;
    7. }
    8. hashmap.set(head.next, true)
    9. head = head.next;
    10. }
    11. return false;
    12. }