2015-05-09 108 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'? –