题解 | #判断链表中是否有环#
判断链表中是否有环
https://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
import java.util.*;
import java.util.Set;
public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null){
return false;
}
//用hashset或者hashset来判断是否有环
HashSet<ListNode> set=new HashSet<>();
while(head!=null){
//如果set包括该节点,说明有环
if(set.contains(head)){
return true;
}
set.add(head);
head=head.next;
}
return false;
}
}
查看13道真题和解析