No enclosing instance of type RemoveNthFromTheEnd is accessible.

错误代码如下: 

public static void main(String[] args) {
		ListNode head = new ListNode(0);
		ListNode n1 = new ListNode(1);
		ListNode n2 = new ListNode(2);
		ListNode n3 = new ListNode(3);
		//System.out.println(new Solution().removeNthFromEnd(head, 1));
	}
class ListNode {
	    int val;
	    ListNode next;
	    ListNode(int x) { val = x; }
} 

原因在于main方法是静态方法,根据Java语法规则(静态嵌套),ListNode没有使用static修饰,故报错。

修改方法有两种,分别如下。

方法一:添加声明内部类为静态类(使用static关键字修饰静态类)

public static void main(String[] args) {
		ListNode head = new ListNode(0);
		ListNode n1 = new ListNode(1);
		ListNode n2 = new ListNode(2);
		ListNode n3 = new ListNode(3);
		//System.out.println(new Solution().removeNthFromEnd(head, 1));
	}
	static class ListNode {
	     int val;
	     ListNode next;
	     ListNode(int x) { val = x; }
	} 

方法二:先实例化外部类,借助外部类实现内部类

public static void main(String[] args) {
		RemoveNthFromTheEnd re = new RemoveNthFromTheEnd();
		ListNode n1 = re.new ListNode(1);
	}
class ListNode {
	    int val;
	    ListNode next;
	    ListNode(int x) { val = x; }
} 

猜你喜欢

转载自blog.csdn.net/zcy_wxy/article/details/86519895