1

从列表中查找并删除所有出现的给定信息。(仅遍历列表一次。)

我可以删除列表中的第一个数字,即如果我选择 1。

并且列表是“1 3 4 6 7” 1 将被删除,并且计数将减少到 4,就像它应该的那样。

public void deleteAll(T deleteItem) {

    LinkedListNode<T> current ; // variable to traverse the list
    LinkedListNode<T> trailCurrent  ; // variable just before current
//  boolean found;



    if (first == null) // Case 1; the list is empty
        System.err.println("Cannot delete from an empty " + "list.");
    else {
        if (first.info.equals(deleteItem)) // Case 2
        {
            first = first.link;

            if (first == null) // the list had only one node
                last = null;
            count--;
        }
    else{
        trailCurrent = first;
        current = first.link;

        while(current != null){
            if(current.info.equals(deleteItem)){
            trailCurrent = current.link;
            count--;
            }
            else
                {
                    trailCurrent = current;
                    current = current.link;
                }
            }

        }
        }
    }
4

3 回答 3

1
public static void deleteKey(LinkedList list, int key) {
    if(list == null) {
        return;
    }

    Node temp = list.head;
    Node prev = null; 
    // If head node itself holds the key or multiple occurrences of key
    while(temp != null && temp.data == key) {
        list.head = temp.next;
        temp = list.head;
    }

    while(temp !=null) {
        if(temp.data == key) {
            prev.next = temp.next;
        } else {
            prev = temp;
        }
        temp = temp.next;
    }
}
于 2017-01-13T17:54:32.290 回答
0

看起来你在删除集合内的元素(不是第一个)时分配的指针有点错误。尝试使用赋值:

trailCurrent.link = current.link;

而不仅仅是:

trailCurrent = current.link;
于 2013-07-06T17:06:13.170 回答
0

您需要将while循环的if子句修复为

if (current.info.equals(deleteItem)) {
  trailCurrent.link = current.link; // deletes current from list
  current = current.link; // updates current pointer
  count--;
}

对于要删除节点 B 的一组三个节点

A --> B --> C
|     |
trail curr

轨迹应保持不变(指向 A);trail.link应该从 A 更改为 C,即curr.link以删除节点 B。除此之外,curr还应该开始指向 C 以进行下一次while循环迭代。

于 2013-07-06T17:07:53.227 回答