从自定义LinkedList类中删除值

时间:2014-08-03 05:46:37

标签: java linked-list nodes

这个自定义类模仿Java的LinkedList类的功能,除了它只占用整数,显然缺少大部分功能。对于这个方法,removeAll(),我将遍历列表的每个节点并删除具有该值的所有节点。我的问题是,当列表中的第一个节点包含要删除的值时,它会忽略同时包含该值的所有后续节点。什么似乎是问题?我是以错误的方式移除前节点吗?例如,[1] - > [1] - > [1]应返回一个空列表,但它离开前节点并且我得到[1]

编辑:它似乎无法删除第二个节点而不是第一个节点。

这是类(将ListNodes存储为列表):

public class LinkedIntList {
    private ListNode front;  // first value in the list

    // post: constructs an empty list
    public LinkedIntList() {
        front = null;
    }

    // post: removes all occurrences of a particular value
    public void removeAll(int value) {
        ListNode current = front; // primes loop
        if (current == null) { // If empty list
            return;
        }
        if (front.data == value) { // If match on first elem
            front = current.next;
            current = current.next;
        }           
        while (current.next != null) { // If next node exists
            if (current.next.data == value) { // If match at next value
                current.next = current.next.next;
            } else { // If not a match
                current = current.next; // increment to next
            }
        }
    }

    // post: appends the given value to the end of the list
    public void add(int value) {
        if (front == null) {
            front = new ListNode(value);
        } else {
            ListNode current = front;
            while (current.next != null) {
                current = current.next;
            }
            current.next = new ListNode(value);
        }
    }

    // Sets a particular index w/ a given value 
    public void set(int index, int value) {
        ListNode current = front;
        for (int i = 0; i < index; i++) {
            current = current.next;
        }
        current.data = value;
    }
} 

这是ListNode类(负责单个“节点”):

//ListNode is a class for storing a single node of a linked
//list.  This node class is for a list of integer values.

public class ListNode {
    public int data;       // data stored in this node
    public ListNode next;  // link to next node in the list

    // post: constructs a node with data 0 and null link
    public ListNode() {
        this(0, null);
    }

    // post: constructs a node with given data and null link
    public ListNode(int data) {
        this(data, null);
    }

    // post: constructs a node with given data and given link
    public ListNode(int data, ListNode next) {
        this.data = data;
        this.next = next;
    }
}

1 个答案:

答案 0 :(得分:0)

实际停留在列表中的[1]元素是第二个元素,它成为代码中的前面元素:

if (front.data == value) { // If match on first elem
    front = current.next;
    current = current.next;
}

之后,您只需遍历列表并删除匹配的元素。 用这个替换有问题的代码应该做的工作:

while (front.data == value) { // If match on first elem
    front = front.next;
    if (front == null) {
        return;
    }
}