第一种解法,每次遍历链表的结点时,都把它加入到哈希集中,由于哈希集中不能存在重复的元素,故当存在环时,遇到了前面已经加入哈希集的结点,使用哈希集的add方法添加失败将返回false
public class Solution {
public boolean hasCycle(ListNode head) {
HashSet<ListNode> set=new HashSet<ListNode>();
while(head!=null){
if(!set.add(head))
return true;
head=head.next;
}
return false;
}
}
第二种解法,快慢指针,慢指针每次移动一个结点,快指针每次移动两个结点,若链表存在环,快指针总会与慢指针相遇
public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null)return false;
ListNode faster=head;
ListNode slow=head;
while(faster.next!=null&&faster.next.next!=null){
/*while语句使用faster.next!=null&&faster.next.next!=null是为了确保faster在每次迭代中
快指针都至少能够移动两步,至于为什么不需要对慢指针slow进行移动非空判断,是因为快指针跑
的比慢指针慢,判断快指针的移动非空情况包含了判断慢指针的移动非空情况*/
slow=slow.next;
faster=faster.next.next;
if(slow==faster)
return true;
}
return false;
}
}