判断链表中是否有环。
快慢指针。
- 时间复杂度O(N),空间复杂度O(1)
- Runtime: 88 ms, faster than 47.27%
- Memory Usage: 41.5 MB, less than 29.33%
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {boolean}
*/
var hasCycle = function(head) {
if (!head || !head.next) return false;
let slow = head;
let fast = head.next;
while (slow !== fast) {
if (!fast || !fast.next) return false;
slow = slow.next;
fast = fast.next.next;
}
return true;
};
网友评论