算法(2)判断链表是否有环
题目描述:
判断给定的链表中是否有环。如果有环则返回true,否则返回false。
代码
1.快慢指针
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode fast = head; //定义快 慢 链表指针
ListNode slow = head;
if(fast == null) { //链表若为空 直接返回false
return false;
}
while(fast != null && fast.next != null) { //当fast或者fast.next为null,表明走到头了,无环
fast = fast.next.next;//fast走两步 slow走一步
slow = slow.next;
if(slow == fast) {//只有slow追上fast 才判定有环
return true; //返回true
}
}
return false; //否则返回false
}
}
2.使用HashSet
//遍历链表,每次判断set中是否有当前链表元素,,不存在添加,存在返回存在环
public static boolean hasCycle(ListNode head) {
Set<ListNode> set = new HashSet<>();
while(head != null) {
if(set.contains(head)) return true;
else {
set.add(head);
head = head.next;
}
}
return false;
}