题目:
给定一个链表,判断链表中是否有环。
进阶:
你能否不使用额外空间解决此题?
分析:
方法一:用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;
}
}