我试图通过反向解析LinkedListNode
时创建一个新的char[]
对象。然后我想链接这些
char[] totalnum = (total + "").toCharArray();
for (int i = totalnum.length; i > 0; i--) {
LinkedListNode sum = new LinkedListNode(totalnum[i]);
sum.next = null;
}
这是我的
LinkedListNode
课:public class LinkedListNode {
int data;
public LinkedListNode next;
// constructor
public LinkedListNode(int newData) {
this.next = null;
this.data = newData;
}
}
我想知道如何去做。我是Java的新手,所以这让我很困惑!我知道我应该在每次迭代中创建一个新的
LinkedListNode
对象,但是据我所知 最佳答案
public class LinkedListNode {
int data;
private LinkedListNode next;
public LinkedListNode(int data) {
this.data = data;
}
public void setNext(LinkedListNode next) {
this.next = next;
}
public LinkedListNode getNext() {
return next;
}
}
char[] totalNum = (total + "").toCharArray();
int length = totalNum.length;
LinkedListNode tail /*or 'head', whatever suits you*/ = new LinkedListNode(totalNum[length - 1]);
LinkedListNode newNode;
LinkedListNode previousNode = tail;
for (int i = length - 2; i >= 0; i--) {
newNode = new LinkedListNode(totalNum[i]);
previousNode.setNext(newNode);
previousNode = newNode;
}