![](/img/trans.png)
[英]Why no tail() or head() method in List to get last or first element?
[英]Method will not replace last element in a list
我有一種方法來替換鏈表中的元素。 它工作正常,但我注意到列表中的最后一個元素沒有被替換。 我想知道我哪里錯了?
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;
}
嘗試遍歷節點並與該值進行比較,如果找到具有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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.