我试图在java中实现我自己的单独链接列表,我希望它是通用的,因为我认为它是最好的选择。然后,我想写一个特定的函数来求和整数的两个链表。问题是由于列表的通用性,我收到错误,我无法检查我的代码...
以下是我的功能代码:
public LinkedList<Integer> sum(LinkedList<Integer> list1, LinkedList<Integer> list2){
// if (list1== null || list2 ==null) return null;
LinkedList<Integer> result = new LinkedList<Integer>();
Node<Integer> node11 = list1.first;
Node<Integer> node22 = list2.first;
int temp = 0;
while (node11.next!=null && node22.next!=null){
int node1 = node11.data;
int node2 = node22.data;
int node3 = (node1 + node2 + temp) %10;
temp = (node1 + node2)>=10 ? 1: 0;
result.insertLast(node3);
node11 = node11.next;
node22 = node22.next;
}
return result;
}
我的两个类有代码:Node和linkedList
class Node<T> {
public T data; // data in Node.
public Node<T> next; // points to next Node in list.
public Node(T data){
this.data = data;
}
}
class LinkedList<T> {
public Node<T> first;
public LinkedList(){
first = null;
}
public void insertLast(T data){
Node<T> newNode = new Node<T> (data); //Creation of New Node.
if(first==null) {
first=newNode;
return;
}
Node<T> tempNode = first;
while(tempNode.next!=null){
tempNode=tempNode.next;
}
tempNode.next=newNode;
}
当我想尝试这段代码时,这是我的主要内容:
LinkedList<Integer> list = new LinkedList();
LinkedList<Integer> list2 = new LinkedList();
list.insertLast(5);
list.insertLast(1);
list.insertLast(3);
list2.insertLast(2);
list2.insertLast(9);
list2.insertLast(5);
LinkedList<Integer> list3 = sum(list, list2);
我得到的错误(我使用ideone作为IDE):
Main.java:179: error: cannot find symbol
LinkedList<Integer> list3 = sum(list, list2);
^
symbol: method sum(LinkedList<Integer>,LinkedList<Integer>)
location: class Ideone
Note: Main.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
您能告诉我错误在哪里以及我应该采取哪些措施来纠正错误?我知道这是由于通用性(因为我不得不在我的函数中使用Integer)。我尝试了一些事情,但没有一个工作......
谢谢!
答案 0 :(得分:0)
在sum方法中使用keywork static:
public static LinkedList sum(LinkedList list1,LinkedList list2){...}
如果你从静态主方法调用sum
答案 1 :(得分:0)
看起来你正在添加两个大整数,每个整数都由一个列表表示。
有两个错误:a)。在函数&#34; sum&#34;中,while循环的终止条件不正确。始终不添加最后两个元素。 B)。在功能&#34;总和&#34; temp表示是否有前一个位置的增加。它没有处理。
考虑BigInteger或java内置List?
答案 2 :(得分:0)
public class ThreadingMulti {
public static void main(String[] args) throws InterruptedException {
LinkedList<Integer> list = new LinkedList();
LinkedList<Integer> list2 = new LinkedList();
list.add(5);
list.add(1);
list.add(3);
list2.add(2);
list2.add(9);
list2.add(5);
LinkedList<Integer> list3 = sum(list, list2);
}
public static LinkedList<Integer> sum(LinkedList<Integer> list1, LinkedList<Integer> list2){
LinkedList<Integer> result = new LinkedList<Integer>();
return result;
}
}
此代码工作正常。 sum方法类型(静态)似乎有问题。请验证您是否可以从静态方法调用非静态方法。