2013-07-12 212 views
0

如何从链接列表中删除元素?从链接列表中删除元素

是不是正确的方法:

public E remove(E element) { 
     Node search = currentNode; 
     boolean nonStop = true; 
     while(((search.previous) != null) && (nonStop)) { 
      if(search.previous.toString().equals(element.toString())) { 
       System.out.println("Item found !!!"); 
       search.previous = search.previous.previous; 
       nonStop = false; 
      } else { 
       search = search.previous; 
      } 
     } 
     currentNode = search; 
     return null; 
    } 

public class Node<E> { 
    public E data; 
    public Node<E> previous; 

    public Node(E data) { 
     this.data = data; 
    } 

    public void printNode() { 
     System.out.println("Node details: "+data); 
    } 

    @Override 
    public String toString() { 
     // TODO Auto-generated method stub 
     return (String)data; 
    } 

} 

当我打印的所有元素的问题是,getAllElements()不给正确的答案,有没有remove()方法或任何问题getAllElements

public void getAllElements() { 
     Node<E> aNode = currentNode; 
     while(aNode != null) { 
      aNode.printNode(); 
      aNode = aNode.previous; 
     } 
    } 
+1

链接列表的细节是什么?它是单链还是双链?它是线性的还是圆形的? – johnchen902

+1

如果标准列表在运行时出现任何不使用的原因? –

+2

如果您想查看您的代码或希望改善您的代码,请在http://codereview.stackexchange.com/上发布您的问题。 –

回答

0

不要你的元素有某种标识符吗? 然后,你可以做到这一点更简单,喜欢这里:remove an object

1

线

if(search.previous.toString().equals(element.toString()) 

调用的节点上,而不是在元素上的字符串。

1

看起来像你的删除方法并没有真正删除任何东西,你应该更新你的方法中的指针,以便没有任何指向要删除的元素,然后垃圾收集器将删除没有任何点的元素至。一些伪代码来说明我的意思:

public remove(Element element){ 
    for (Element e : myLinkedList){ 
    if (e.equals(element)){ 
     if (next != 0) 
     previousPtr = nextPtr; 
     else 
     previousPtr = null; 
    } 
    } 
} 

注意这是正确的Java代码,只是伪代码给你一个想法,我节省一些乐趣,为你! :)

1

试试这个:

public void remove(E element) 
{ 
    Node n = head; // This is the head of the linked list-- It is the starting node of your linked list: For your case "currentNode" 
    Node tmp; 
    while(n!=null && !n.data.equals(element)) 
    { 
     tmp = n; 
     n = n.previous; 
    } 

    if(n==null) 
    { 
     // Do your stuff 
     System.out.println("Element "+element+" not found."); 
    } 
    else 
    { 
     // Do your stuff 
     tmp.prev = n.prev; 
     n.prev = null; 
     System.out.println("Element "+element+" removed."); 
    } 
} 


// Suggestion: This method name should be "printList()" 
public void getAllElements() 
{ 
    Node n = head;  // In your case: "currentNode" 
    while(n!=null) 
    { 
     n.printNode(); 
     n = n.previous; 
    } 
} 
0
public E remove(E element) { 
     Node search = currentNode; 
     boolean nonStop = true; 
     while(((search.previous) != null) && (nonStop)) { 
      if(search.previous.data.equals(element)) { 
       System.out.println("Item found !!!"); 
       search.previous = search.previous.previous; 
       nonStop = false; 
      } 
      search = search.previous; 
     } 
     return null; 
    } 

我发现该问题的解决,感谢大家对你的一种支持。