判断节点有无环路
class ListNode {val: number;next: ListNode | null;constructor(val?: number, next?: ListNode | null) {this.val = val === undefined ? 0 : val;this.next = next === undefined ? null : next;}}function hasCycle(head: ListNode | null): boolean {let slow = head;let fast = slow;/*快慢指针必然相遇, 但相遇点不一定是入环的点。*/while (fast !== null && fast.next !== null) { // 必要条件slow = slow!.next;fast = fast.next.next;if (slow === fast) {return true;}}return false;}
hashmap
function hasCycle1(head: ListNode | null): boolean {let hashmap: Map<ListNode, boolean> = new Map();while (head && head.next) {if (hashmap.has(head.next)) {//head.next 已经在hashpmap 中, 那么这个next必然是入环点return true;}hashmap.set(head.next, true)head = head.next;}return false;}
