方法不会替换列表中的最后一个元素

时间:2020-06-08 19:48:20

标签: java

我有一种替换链表中元素的方法。它工作正常,但是我注意到列表中的最后一个元素没有被替换。我想知道我要去哪里错了?

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;

    }

1 个答案:

答案 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;
    }