我试图将两个由链表表示的数字相加.我有静态说明符和内部类的问题.我定义了一个内部类SumWrapper来跟踪进位.我在sum方法中使用了这个包装器.我首先将它声明为静态方法,但我在Eclipse上遇到以下错误:
不能访问类型为Solution的封闭实例.必须使用类型为Solution的封闭实例限定分配(egxnew A(),其中x是Exo25V2的实例).
然后我删除了静态说明符,但它无法从main调用我的方法...
有解决方法吗?
public class Solution {
public class SumWrapper{
public int carry = 0;
public Node node;
public SumWrapper(int c, Node n){
carry = c;
node = n;
}
} // close sumWrapper class
public SumWrapper sum(Node node1, Node node2){
if (node1 == null && node2 == null){
SumWrapper result = new SumWrapper(0, null);
return result;
}
int current = node1.data + node2.data + sum(node1.next, node2.next).carry;
int carry = (current >= 10) ? 1 : 0;
current = current % 10;
Node sumResult = new Node(current);
sumResult.next = sum(node1.next, node2.next).node;
SumWrapper result = new SumWrapper(carry, sumResult);
return result;
} // close sumWrapper method
public int listSize(Node node){
int result = 0;
while (node != null){
result++;
node = node.next;
}
return result;
} // close listSize method
public Node sumLists(Node node1, Node node2){
int size1 = listSize(node1);
int size2 = listSize(node2);
int size = (size1 >= size2) ? (size1+1):(size2+1);
while (size1 < size){
Node head1 = new Node(0);
head1.next = node1;
node1 = head1;
size1++;
}
while (size2 < size){
Node head2 = new Node(0);
head2.next = node2;
node2 = head2;
size2++;
}
SumWrapper wrap = sum(node1, node2);
return wrap.node;
} // close sumLists method
public static void main(String[] args){
Node head1 = new Node(6);
head1.appendToTail(1);
head1.appendToTail(1);
head1.appendToTail(7);
Node head2 = new Node(2);
head2.appendToTail(9);
head2.appendToTail(5);
Node result = sumLists(head1, head2);
Node.printLinkedList(result);
} // close main method
}
Run Code Online (Sandbox Code Playgroud)
问题是您正在sumLists从您的main方法调用非静态方法().该main方法是静态的,因此只能访问同一类中的其他静态方法.
除非......你创建了一个例子Solution:
public static void main(String... args) {
Solution s = new Solution();
s.sumLists(...); // now you invoke it using an instance method (i.e. a non-static method)
}
Run Code Online (Sandbox Code Playgroud)
所以,你的选择是:
有关这方面的一些好的阅读,请查看Oracle教程