2015-05-09 107 views
1

我的方法是首先在列表中找到某個元素,如果爲true,則該節點包含的值將移動到列表的前面,而不創建或刪除新的節點。我到目前爲止,我不認爲移動節點部分正在工作,任何幫助表示感謝!將項目移動到LinkedList的前面

public boolean findMove(E e){ 
    Node previous=null; 
    Node current=head; 
    while(current !=null){ 
     if(e.equals(current.item)){ 
      previous.next=current.next; 
      current.next=head; 
      head=current; 
      System.out.println("True"); 
      return true; 
     } 
     current=current.next; 
    } 
    System.out.println("False"); 
    return false; 
} 
+0

你不是在循環更新'previous'。 –

+0

@John請嘗試我的答案,如果它適合你? –

+0

絕對需要'boolean'' return還是可以拋出'NoSuchElementException'?這方面阻礙了你做這個非常乾淨簡潔的方式的能力。 – ChiefTwoPencils

回答

1

你能試試嗎?看來你並沒有更新previous

public boolean findMove(E e){ 
    Node previous=head; 
    Node current=head; 
    while(current !=null){ 
     if(e.equals(current.item)){ 
      //Found the item 
      previous.next=current.next; 
      current.next=head; 
      head=current; 
      System.out.println("True"); 
      return true; 
     } 
     previous = current; 
     current=current.next; 
    } 
    System.out.println("False"); 
    return false; 
} 
+0

謝謝!很好的幫助! – Katherine

+0

您可能還需要驗證邊界條件的代碼。它可能在這裏和那裏需要一些小的改變。很高興能幫到你:) –

0

很少有什麼問題與您的代碼:

  • 在循環中,參考頭不存儲任何地方。假設,頭是起點,你不應該改變它。但是在循環內部,由於「當前」更新爲指向下一個節點,因此head不再是LinkedList的有效起點。
  • 如果您在第一個位置(頭節點)找到該項目,那麼您不應該移動它(檢查previous = null)。

有了上面的東西試試這個:

public boolean findMove(E e){ 
    Node previous=null; 
    Node current=head; 
    Node headerNode = head; 
    while(current !=null){ 
     if(e.equals(current.item) && previous != null){ 
      // Update the previous node to point to the next node 
      previous.next=current.next; 
      // Move the current node to point to the starting position 
      current.next=headerNode; 
      // Mark the current node as header node 
      headerNode=current; 

      System.out.println("True"); 
      return true; 
     } 
     // Not found - Update Previous to point the current node 
     previous = current; 
     current=current.next; 
    } 
    System.out.println("False"); 
    return false; 
} 
+0

爲什麼你需要'previous!= null'條件?請解釋。 –

+0

如果正在搜索的元素是頭節點本身,則前一個元素仍然是「空」。訪問'previous.next'會拋出空指針異常。 –

+0

您如何將'current'和'previous'指向'head'? –