删除LinkedList中的链接

时间:2015-06-17 06:18:02

标签: java linked-list

您好我有以下代码我试图从LinkedList删除链接。我能够删除节点,但每当我尝试遍历列表时,它都会给我原始计数。有人可以帮我吗?

//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;
    }
}

}

2 个答案:

答案 0 :(得分:0)

first = first.nextLink.nextLink;

不会更改链接列表的结构,因为您将first设置回最后的原始值(first = firstLink;)。

要删除链接,您应更改已删除链接之前链接的first.nextLink

first.nextLink = first.nextLink.nextLink;

您的代码也有其他问题。它没有正确处理第一个链接的删除,它可能抛出NullPointerException。

答案 1 :(得分: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;
}