问题描述:
Given head, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail’s next pointer is connected to. Note that pos is not passed as a parameter.
Return true if there is a cycle in the linked list. Otherwise, return false.
Constraints:
The number of the nodes in the list is in the range [0, 10^4].
-105 <= Node.val <= 105
pos is -1 or a valid index in the linked-list.
判断链表是否有循环点
暴力算法:
因为最多有100000个点,所以循环100000遍以后还没找到next=null,则证明必有循环。
public class Solution {
public boolean hasCycle(ListNode head) {
for (int i=0; i<100000; i++){
if (head==null) return false;
head = head.next;
}
return true;
}
}
用hashset
用hashset和具体的val无关,把每个node的指针存放在hashset中,若没遇到同样的指针,则说明未成环,需要加入set,否则遇到相同的地址说明成环。
代码如下:
public class Solution {
public boolean hasCycle(ListNode head) {
Set<ListNode> hset = new HashSet<>();
//if (head==null) return false;
while(head!=null){
if (!hset.contains(head)){
hset.add(head);
head=head.next;
}
else{
return true;
}
}
return false;
}
}