[英]How do I remove the only node in a linked list in java?
我有一個while循環,應該運行直到從鏈接列表中刪除某個值為止。(remainingPoints)問題是,如果該節點是鏈接列表中的唯一節點,我的編譯器將給我一個錯誤。 編輯:我正在使用Java中的預寫的鏈表類。
while (remainingPoints.contains(endPoint)) {
//loop through each index of the start points adjacency array and update the path estimates.
for (int i = 0; i < maxIndex; i++) {
//if the path estimate is greater than the distance found from the next Point to the
//i'th point, update the pathEstimate for that point and update the parent of the point.
if ((pathEstimates[i] != 0 && adjMatrix[next][i] != 0) && (adjMatrix[next][i]+pathEstimates[next] < pathEstimates[i])) {
pathEstimates[i] = adjMatrix[next][i] + pathEstimates[next];
parents[i] = next;
}
}
//reset next.
next = -1;
//This will be the intersection that has the shortest path from the last tested
//intersection (that is not 0).
for (int i = 0; i < maxIndex; i++) {
if (pathEstimates[i] != 0 && remainingPoints.contains(i)) {
if (next == -1)
next = i;
else if (pathEstimates[i] < next)
next = i;
}
}
//Inelegent solution goes here in place of the line of code below:
remainingPoints.remove(next);
}
我嘗試過的一個優雅解決方案是在此if語句中添加一個包含無用的包含-1的節點,以便可以刪除包含next的節點,從而使while循環的下一次迭代為false,但這增加了一個更奇怪的問題:
if (remainingPoints.size() == 1)
remainingPoints.add(-1);
System.out.println(next);
System.out.println(remainingPoints.remove(next));
使用此嘗試的解決方案,循環將無限運行。 打印的next的值是1(這是next的正確和預期值),但不出所料,remainingPoints.remove(next)的值是-1。 我也測試了其他值,remainingPoints.remove(next)的值始終是我使用if語句添加的值。 這表明remove方法正在刪除我添加的值,這將解釋無限循環,但是為什么會這樣呢?
如果有人能解釋如何簡單地刪除Java鏈表中的唯一節點,將不勝感激! 凡是能夠解釋上述錯誤的人,都將獲得獎金。
順便說一句,這是我關於堆棧溢出的第一篇文章,因此,如果我犯了任何發布錯誤或對堆棧溢出禮節不了解,請告訴我!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.