题目:
思路:遍历链表,将链表中的每一个值存入HashSet中,假如Set对象已经包含了head的值,则说明此表是循环链表,若没有,则将遍历值存入Set对象中,链表指向下一个,依次循环即可。
代码:
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public 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;
}
}
运行情况: