我有一种替换链表中元素的方法。它工作正常,但是我注意到列表中的最后一个元素没有被替换。我想知道我要去哪里错了?
public class ListOfNVersion03PartB
{
private int thisNumber; // the number stored in this node
private ListOfNVersion03PartB next; // forms a linked list of objects
private final int nodeID; // a unique ID for each object in the list
private static int nodeCount = 0; // the number of list objects that have been created
public ListOfNVersion03PartB(int num)
{
thisNumber = num;
next = null;
++nodeCount;
nodeID = nodeCount;
}
public int replaceOnce(int replaceThis, int withThis)
{
int count = 0;
if( (next!= null) && (thisNumber == replaceThis) ){
thisNumber= withThis;
return count =1;
}
if( (next!= null) && (thisNumber != replaceThis) ){
return next.replaceOnce(replaceThis,withThis);
}
else
return count;
}
答案 0 :(得分:0)
尝试遍历该节点并与该值进行比较,如果找到具有replaceThis
值的节点,则进行替换
public int replaceOnce(int replaceThis, int withThis) {
ListOfNVersion03PartB current = this;
int count = 0;
while (current != null) {
if (current.thisNumber == replaceThis) {
current.thisNumber = withThis;
count++;
}
current = current.next;
}
return count;
}