пытается выполнить замену в связанном списке, но программа заменяет только первый элемент - PullRequest
0 голосов
/ 29 мая 2020

Мой текущий код заменяет только первый элемент связанного списка. Я пытаюсь создать метод замены с двумя параметрами, но не могу. Мой текущий logi c показывает, что я пытаюсь заменить элемент своим новым вводом, но я предполагаю, что мне не удается пройти по списку, поскольку заменяется только первый.

public class ListOfNVersion03PartA
{   
    private int thisNumber;              // the number stored in this node
    private ListOfNVersion03PartA next;  // forms a linked list of objects
    private int []list;
    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

    /**
     * @param  num   the value to be stored in this object
     */
    public ListOfNVersion03PartA(int num)
    {
        thisNumber = num;
        next = null;

        ++nodeCount;
        nodeID = nodeCount;

    }



 public ListOfNVersion03PartA(int [] num)
{

    this(num[0]);  // in this context, "this" invokes the other constructor    
    list = new int[num.length];
    for (int i=1 ; i<num.length ; ++i)
        {
        insertLast(num[i]);
        }
}

 public int replaceAll(int replaceThis, int withThis)
        {
            int count = 0; 
            int x = 0;


        for ( int i=0 ; i < nodeCount; ++i) 
        {
            if ( thisNumber == replaceThis )
        {
            thisNumber = x;
            x = withThis;
            ++count;

        }
        }

        return count;
    }

1 Ответ

0 голосов
/ 29 мая 2020

После того, как вы оценили текущий узел (он же this), вы должны выполнить оценку следующего узла, пока не останется больше узлов для оценки. Вот пример с вашим текущим кодом:

public int replaceAll(int replaceThis, int withThis) {
    int result = 0;
    if (thisNumer == replaceThis) {
        thisNumber = withThis;
        result = 1;
    }
    if (next != null) {
        result += next.replaceAll(replaceThis, withThis);
    }
    return result;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...