判断链表是否有环
给你一个链表的头节点 head ,判断链表中是否有环。
力扣链接
https://leetcode.cn/problems/linked-list-cycle/
方法一:哈希表
哈希表的add方法如果添加成功会返回true,如果将重复的元素添加到哈希表中会添加失败返回false
public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null||head.next==null){
return false;
}
Set<ListNode> s=new HashSet<>();
while(head!=null){
if(!s.add(head)){
return true;
}
head=head.next;
}
return false;
}
}
方法二:快慢指针
定义快慢指针,快指针每次走两步,慢指针每次走一步,如果快慢指针能够相遇就说明有环。
public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while (slow != fast) {
if (fast == null || fast.next == null) {
return false;
}
slow = slow.next;
fast = fast.next.next;
}
return true;
}
}