题目:
给定一个链表,判断链表中是否有环。
进阶:
你能否不使用额外空间解决此题?
分析:
方法一:用HashSet把已访问过的节点存起来
方法二:快慢指针追击,如果慢指针能追上快指针,那一定成环。若不成环,则最后一定能结束遍历
JavaCode
HashSet
public class Solution {
public boolean hasCycle(ListNode head) {
Set<ListNode> s=new HashSet<ListNode>();
while(head!=null){
if(!s.contains(head)){
s.add(head);
head=head.next;
}
else{
return true;
}
}
return false;
}
}
快慢指针追击
public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null)return false;
ListNode slow=head;
ListNode fast=head.next;
while(fast!=null&&fast.next!=null){
if(slow==fast)return true;
slow=slow.next;
fast=fast.next.next;
}
return false;
}
}
本文介绍两种链表环检测方法:一是使用HashSet记录已访问节点;二是采用快慢指针技术,通过指针速度差异判断是否存在环。这两种方法分别适用于不同场景,并探讨了如何在不使用额外空间的情况下解决该问题。
304

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



