我有一个项目,我一直在努力,我使用链表创建一个没有限制其大小的整数值。这是通过将String传递给构造函数来完成的,然后链表的每个节点都包含3位数字。字符串值将转换为整数。 我正在努力的地方是迭代字符串并正确地将节点添加到节点。此外,该号码应以相反的顺序存储,例如,如果号码为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个节点。我确信这是一件非常微不足道的事情,我很遗憾,但我们非常感谢任何建议或意见。谢谢。
答案 0 :(得分:0)
让我们在这里做一些追踪
132456789123456789123456789
虽然使用substring
方法的i+=3
方法将用于第一个循环,因此
headData = digits.substring(0,3)
这意味着结果将是这样的
loopNo resultOfSubString deletedDigit
1 132 -
2 567 4
3 912 8
4 456 3
5 891 7
6 345 2
7 789 6
the printed nodes
您应该在每个循环结束时将i
的值减1。