gpt4 book ai didi

java - 尝试在链表中执行替换方法,但程序仅替换第一个元素

转载 作者:行者123 更新时间:2023-12-01 16:28:49 24 4
gpt4 key购买 nike

我当前的代码仅替换链表的第一个元素。我试图创建一个带有两个参数的替换方法,但失败了。我当前的逻辑表明,我正在尝试用新输入替换该元素,但我假设我无法遍历列表,因为只有第一个元素被替换。

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

最佳答案

评估当前节点(又名 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;
}

关于java - 尝试在链表中执行替换方法,但程序仅替换第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62090002/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com