2015-06-17 237 views
0

嗨我有以下代码,我试图从链接列表中删除链接。我可以删除节点,但每当我尝试遍历列表时,它都会给我原来的计数。有人可以帮我吗?删除链接列表中的链接

//Code from a different Class where I have created an object of the LinkedList class 
    ll.deleteLinkNumber(6); 


//Code from the LinkedList Class 
public void deleteLinkNumber(int linkNumber) { 

    //Link lastLink = getLastLink(); 

    Link currentLink = first; 
    Link firstLink = currentLink; 
    int linkCount = 1; 



    while (first != null) { 
     if (linkCount == linkNumber) { 
      first = first.nextLink.nextLink; 
      System.out.println("Deleted one link: " + linkCount); 
     } 
     else { 
      first = first.nextLink; 
      System.out.println("Not deleting: " + linkCount); 
     } 
     linkCount++;  
    } 
    first = firstLink; 
    System.out.println("dd" + first.nextLink.nextLink.nextLink.nextLink.nextLink.dataElementInt); 




    //first.nextLink.nextLink.nextLink = first.nextLink.nextLink.nextLink.nextLink.nextLink; 

    /* 
    int count = getLinkedListCount(first); 
    Link firstLink = first; 
    Link currentLink = first; 

    first.nextLink.nextLink.nextLink = first.nextLink.nextLink.nextLink.nextLink; 

    System.out.println("Count of initial list: " + count); 

    while (currentLink !=null) { 
     if (count-linkNumber != 1) { 
      currentLink = currentLink.nextLink; 
      System.out.println("Not deleting: " + count); 
     } 
     else { 
      currentLink = currentLink.nextLink.nextLink; 
      System.out.println("Deleted one link: " + count); 
     } 
     count--; 
    } 
    */ 
} 


public void printList() { 
    /* 
     In the class LinkedList, first is always the first link from the LEFT. For example below 
     ThirdLink->SecondLink->FirstLink.nextLink = null; 
     first = ThirdLink; 
    */ 

    Link currentLink = first; 
    int count = 1; 
    while (currentLink != null) { 
     currentLink.printLink(count); 
     count++; 
     currentLink = currentLink.nextLink; 
    } 
} 

}

回答

0
first = first.nextLink.nextLink; 

不会改变链表的结构,因为在结尾(first = firstLink;)设置first回原来的值。

为了删除您应该更改删除链接之前在链接的first.nextLink链接:

first.nextLink = first.nextLink.nextLink; 

你的代码有其他的问题。它不会正确处理第一个链接的删除,并且可能会抛出NullPointerException。

0

这条线:

first = first.nextLink 

正在修改字段,即使你打算只是循环,从而找到正确的链接。这似乎是一件很奇怪的事情。

我希望有这样的:

public void deleteLinkNumber(int linkNumber) { 
    Link previous = null; 
    Link current = first; 

    for (int i = 0; i < linkNumber && current != null; i++) { 
     previous = current; 
     current = current.nextLink; 
    } 
    if (current == null) { 
     throw new IllegalArgumentException("No such link"); 
    } 

    // Delete first link? Just change the head. 
    if (previous == null) { 
     first = first.nextLink; 
     return; 
    } 

    // Anything else - just change the link. 
    previous.nextLink = current.nextLink; 
}