2014-07-01 83 views
0

我有一個while循環,應該運行,直到從我的鏈表中刪除某個值。(remainingPoints)問題是如果該節點是鏈表中唯一的節點,我的編譯器會給我一個錯誤。編輯:我在java中使用預寫的鏈接列表類。如何刪除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); 

    } 

一個不雅的解決辦法我試過是其中添加含有-1,使得包含下一節點可以刪除使while循環的下一次迭代虛假無用的節點這個if語句添加,但添加了一個更好奇的問題:

if (remainingPoints.size() == 1) 
      remainingPoints.add(-1); 
    System.out.println(next); 
    System.out.println(remainingPoints.remove(next)); 

有了這個嘗試解決方案,循環無限運行。下一個打印的值是1(這是下一個的正確值和預期值),但不知何故remainingPoints.remove(next)的值爲-1。我也測試了其他值,剩下的Points.remove(next)值始終是我使用if語句添加的值。這表明remove方法正在刪除我添加的值,這將解釋無限循環,但爲什麼會發生這種情況?

如果有人可以解釋如何簡單地刪除java中的鏈表中的唯一節點,將非常感謝!誰也可以解釋上述錯誤的獎金。另外,這是我的第一篇關於堆棧溢出的文章,所以如果我發佈了任何發佈錯誤或者對任何堆棧溢出禮儀都無知,請讓我知道!

+0

爲什麼不只是檢查head-> next是否爲null,如果是,那麼檢查頭部的值是否是您正在搜索的值,將其刪除並返回null或者什麼也不做? –

+0

我剛開始在java中編碼,並且是一個開始的程序員,所以也許這是一個愚蠢的問題,但你將如何刪除節點並返回null?如果我使用C語言編寫的話,那對我來說是非常有用的建議,但是我在java中使用了預先編寫的鏈接列表類,而且我沒有看到任何方法去除鏈表中的唯一節點。 – user3792733

+0

哦,你沒有在你的問題中提到過,只需將頭部的內容設置爲空即可。像list.remove(0) –

回答

1

檢查是否頭戴式>下一個爲空或不是,如果是則檢查是否在頭部值是您正在搜索的價值,將其取出並返回null或其他什麼都不做

你可以使用此語法將其刪除: -

list.remove(0); 

考慮到列表是您的LinkedList,我也建議閱讀一般列表和集合Jenkov's tutorials,幫助您掌握這一點。當我開始使用Java時,他們幫助了我很多。我把它們聯繫起來了。請隨時問問題,並歡迎堆棧溢出!