判断链表是否为环: 快指针移动两步,慢指针移动一步,快慢指针相遇即是环
class HuanLinkedList {
func isHuanLinkedList(_ list: LinkList<Int>) -> Bool {
if list.isEmpty {
return false
}
// 快慢指针
let slowPtr = list.first
let fastPtr = list.first
while let slowPtr = slowPtr?.next, let fastPtr = fastPtr?.next?.next, slowPtr == fastPtr {
return true
}
return false
}
}