Appearance
141. 环形链表
快慢指针的思想
js
/**
* 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 == null) return false
// 定义快慢指针
let slow = head
let fast = head.next
// 循环自己
while(fast !== null && fast.next !== null) {
// 如果快慢指针重合,说明有环,操作结束
if (slow == fast) {
return true
}
// 慢指针步长是1
slow = slow.next
// 快指针步长是2
fast = fast.next.next
}
// 都循环完成就说明不是环形链表
return false
};
最好这么写
js
/**
* @param {ListNode} head
* @return {boolean}
*/
var hasCycle = function(head) {
if (head === null) return false
let fast = head
let slow = head
while(fast !== null && fast.next !== null) {
fast = fast.next.next
slow = slow.next
if(fast === slow) return true
}
return false
};