报错:No enclosing instance of type _141_环形链表 is accessible. Must qualify the allocation with an enclosing instance of type _141_环形链表 (e.g. x.new A() where x is an instance of _141_环形链表).
报错描述:
没有封闭的实例类型_141_环形链表是可访问的。必须有资格分配一个封闭的实例类型_141_环形链表(例如x.new的(),x是一个实例_141_环形链表)。
最近在刷LeetCode的时候,在刷题过程出现这样一个问题。查了一下相关资料,原来我原先定义的内部类是动态的,然而main方法是静态的,静态方法不能直接调用动态方法,要先创建外部类然后才可以调用内部动态方法,或者是直接在内部类前面加上static,也可。
总结一下:静态方法main不能直接调用内部类,因为内部类是动态的(public class开头的),在main中调用的两种方法:
1、new外部类,再new内部类中的动态方法
EqualsObject.Transport obj1 = new EqualsObject().new Transport();
_141_环形链表.ListNode node = new _141_环形链表().new ListNode(3);
2、在内部类前面加上static
static class ListNode{
int value;
ListNode next;
ListNode(int val){
this.value = val;
this.next = null;
}
}
总的代码:
public class _141_环形链表 {
class ListNode{
int value;
ListNode next;
ListNode(int val){
this.value = val;
this.next = null;
}
}
public boolean hasCycle(ListNode head) {
if(head == null || head.next == null) {
return false;
}
ListNode fast = head.next;
ListNode slow = head;
while(fast != null && fast.next != null) {
if(fast == slow) {
return true;// 快慢相遇 说明肯定有环
}
fast = fast.next;
slow = slow.next;
}
return false;
}
public static void main(String[] args) {
_141_环形链表.ListNode node = new _141_环形链表().new ListNode(3);
}
}
参考:
https://blog.csdn.net/sunny2038/article/details/6926079