删除两个链表中具有相同数据的节点

Deleting Node with same data in 2 LinkedLists

正如标题所说,我想比较 2 个链接列表(完成和工作)并且我想删除具有相同值的节点仅在列表 2 ..我写了一个代码并试了一下,它在特定的工作案例,但我似乎无法理解它发生了什么(给出错误的输出)。我使用的想法是在一个节点上粘贴一个 LinkedList,将其与另一个列表中的所有节点进行比较,然后在发现它们相等时删除。

这里是删除头代码:

public void deleteHead() {
    if (head != null) {
        head = head.getNext();
    }
}

这里是 CompareTo 代码:

public int compareTo(NodeData nd) {
    if (num == nd.getNum()) {
        return 0;
    }
    if (num != nd.getNum()) {
        return -1;
    }
    return 1;
}

这是删除方法

public void delete(LinkedList LL) {
    Node curr = head;
    Node curr2 = LL.head;
    while (curr2 != null) { //To traverse LL when list1 is done traversing
        while (curr != null) { //traverse list1 while checking for common Nodes to delete

            if (curr2.getData().compareTo(curr.getData()) == 0) { //compare data in the Nodes
                System.out.println(curr2.getData().getNum() + " FOUND, WILL BE DELETED");
                deleteHead(); //delete the current node of list1
                curr = curr.getNext();
                break;
            }
            else if (curr2.getData().compareTo(curr.getData()) == -1 ){
                System.out.println(curr2.getData().getNum() + " Doesn't Match");}
            curr = curr.getNext(); //next node in list1
        }
        curr2 = curr2.getNext(); //next node in LL
    }
}

我尝试了一个简单的输出:

Output

如果两个节点的数据相等,您将删除其中一个列表的头部而不是当前节点。

其次,你应该将第一个列表的每个元素与第二个列表的每个元素进行比较,内部 while 循环将迭代并使用第二个列表,当它再次被调用时 - 将没有任何可迭代的东西,所以你应该改变:

while (curr2 != null) { //To traverse LL when list1 is done traversing
        while (curr != null) { //traverse list1 while checking for common Nodes to delete

至:

while (curr2 != null) { 
    Node curr = head; // <-- pay attention here, every loop you need to start from the beginning! 
    while (curr != null) { 
        if ... {
            delete(curr); // TODO: need to implement this method in your LinkedList class
        else {
             ...