https://leetcode-cn.com/problems/linked-list-cycle/
import scala.collection.mutable.HashSet
object Solution {
/**
* 哈希表法
*/
def hasCycle(head: ListNode): Boolean = {
if(head == null || head.next == null){
false
}else{
val visted_node = new HashSet[ListNode]()
var flag = true
var prev = head
while(prev != null && flag){
if(visted_node.contains(prev)){
flag = false
}else{
visted_node.append(prev)
prev = prev.next
}
}
!flag
}
}
/**
* 快慢指针法
*/
def hasCycle(head: ListNode): Boolean = {
if(head == null || head.next == null){
false
}else {
var flag = true
var slow = head
var fast = head.next
while(slow != fast && flag){
if(fast == null || fast.next == null){
flag = false
}
if(flag){ //防止指针越界
slow = slow.next
fast = fast.next.next
}
}
flag
}
}
}
Scala检测链表环(leetCode 141)
使用哈希表与快慢指针解决链表环问题
最新推荐文章于 2025-11-24 15:22:28 发布
该博客介绍了两种方法解决链表中环的检测问题:一是利用哈希表记录已访问节点,二是通过快慢指针进行遍历。这两种算法都是在O(n)的时间复杂度内完成,有效地检测链表中是否存在环。文章详细解释了每种方法的实现逻辑,并提供了Scala代码示例。
297

被折叠的 条评论
为什么被折叠?



