在java中向链表添加未知数量的节点
我有一个我一直在做的项目,我使用一个链表来创建一个不受大小限制的整数值。通过将字符串传递到构造函数中,然后链表的每个节点都包含3位数字。字符串值将转换为整数。 我正在努力通过字符串进行迭代,并正确地将int添加到节点。此外,数字应以相反的顺序存储,例如,如果数字为123456,则列表将有2个节点。头部为654,第二个节点(尾部)为321
这是我当前的构造函数代码
public UnboundedInt(String digits){
head = null;//head of list
tail = head;//tail of list
cursor = null;//current node of list
precursor = null;//node previous to current
manyNodes = 0;//number of nodes in the list
String headData;
for(int i = 0; i < digits.length(); i ++){
headData = digits.substring(i,i+=3);//creates substring of next 3
//digits
int dataHold = Integer.parseInt(headData);//converts substring to int
//value
IntNode temp = new IntNode(dataHold,null);
temp.setLink(head);
head = temp;
manyNodes++;//increases number of nodes
}
}
我使用132456789123456789123456789作为测试值,它当前在调试中告诉我,我只有7个节点,它们当前存储为 789 891 456 912 567 132. 这应该是9个节点。我确信我遗漏了一些非常琐碎的东西,但是我非常感谢你的任何建议。多谢各位
# 1 楼答案
让我们在这里做一些跟踪
虽然
substring
方法使用i+=3
,但该方法将用于第一个循环,如下所示headData = digits.substring(0,3)
这意味着结果会是这样
在每个循环结束时,应将
i
的值递减1