The following problems were encountered today when compiling Java programs:
No enclosing instance of type Printlistfromtailtohead is accessible. Must qualify the allocation with a enclosing instance
of type printlistfromtailtohead (e.g. X.new A () where x is A instance of Printlistfromtailtohead).
The source code is:
public class Printlistfromtailtohead {public
static void Main (string[] args) {
ListNode one = new ListNode (1);
listnode two = new ListNode (2);
ListNode three = new ListNode (3);
One.next = two;
Two.next = three;
arraylist<integer> result = Printlistfromtailtohead (one);
SYSTEM.OUT.PRINTLN ("Results are:" + result);
}
Class ListNode {public
int val;
Public ListNode next;
Public ListNode () {
} public
listnode (int val) {
this.val = val;
}
}
public static arraylist<integer> Printlistfromtailtohead (ListNode listnode) {
stack<integer> Stack = New Stack<integer> ();
while (ListNode!= null) {
stack.push (listnode.val);
ListNode = Listnode.next;
}
arraylist<integer> ArrayList = new arraylist<integer> ();
while (!stack.isempty ()) {
Arraylist.add (Stack.pop ());
}
Return arrayList
}
}
Question Explanation:
In the code, my ListNode class is the inner class defined in the Printlistfromtailtohead class. The listnode inner class is a dynamic inner class, and my main method is static.
Just like a static method cannot invoke a dynamic method.
There are two ways to solve this problem:
First type:
Defines the inner class ListNode as a statically static class.
The second type:
The inner class ListNode are defined outside the Printlistfromtailtohead class.
Two ways to solve this problem:
First type:
public class Printlistfromtailtohead {public
static void Main (string[] args) {
ListNode one = new ListNode (1);
listnode two = new ListNode (2);
ListNode three = new ListNode (3);
One.next = two;
Two.next = three;
arraylist<integer> result = Printlistfromtailtohead (one);
SYSTEM.OUT.PRINTLN ("Results are:" + result);
}
Static class ListNode {public
int val;
Public ListNode next;
Public ListNode () {
} public
listnode (int val) {
this.val = val;
}
}
The second type:
public class Printlistfromtailtohead {public
static void Main (string[] args) {
ListNode one = new ListNode (1);
listnode two = new ListNode (2);
ListNode three = new ListNode (3);
One.next = two;
Two.next = three;
}
public static arraylist<integer> Printlistfromtailtohead (ListNode listnode) {
stack<integer> Stack = New Stack<integer> ();
while (ListNode!= null) {
stack.push (listnode.val);
ListNode = Listnode.next;
}
arraylist<integer> ArrayList = new arraylist<integer> ();
while (!stack.isempty ()) {
Arraylist.add (Stack.pop ());
}
Return arrayList
}
}
Class ListNode {public
int val;
Public ListNode next;
Public ListNode () {
} public
listnode (int val) {
this.val = val;
}
}
The above is a small set to introduce the Java solution No enclosing instance of type Printlistfromtailtohead is accessible the problem of two scenarios, I hope to help.