Java Linked List指针混乱

时间:2017-12-13 05:31:12

标签: java pointers linked-list

下面的代码来自java LinkedList实现。该方法在列表的索引点添加一个字符串元素,并从我的一本书中获取。

链表类有2个全局私有变量

Node first;
Node last;


public void add(int index, String e) {
    if (index < 0 || index > size()) {
        String message = String.valueOf(index);
        throw new IndexOutOfBoundsException(message);
    }

    // Index is at least 0
    if (index == 0) {
        // New element goes at beginning
        first = new Node(e, first);
        System.out.println("ran");
        if (last == null)
            last = first;
        return;
    }

    // Set a reference pred to point to the node that
    // will be the predecessor of the new node
    Node pred = first;
    for (int k = 1; k <= index - 1; k++) {
        pred = pred.next;
    }

    // Splice in a node containing the new element
    pred.next = new Node(e, pred.next);
    System.out.println(toString());

    // Is there a new last element ?
    if (pred.next.next == null)
        System.out.println("ran");
        last = pred.next;
}

我的问题
我不明白Node first, last如何在以下条件下更新

假设您有一个类似于["1","2","3","7","4","5,"6"]

的列表

然后将元素“4”添加到索引3

因此,该列表看起来像["1","2","3","4","7","4","5,"6"],但查看添加方法的代码我不知道第一个最后节点指针得到更新。因为在我看来这些是唯一运行的代码片段,因为索引不是0而最后一个不会改变

修改

在toString方法(未显示)中使用对象节点first来遍历集合

    // Set a reference pred to point to the node that
    // will be the predecessor of the new node
    Node pred = first;
    for (int k = 1; k <= index - 1; k++) {
        pred = pred.next;
    }
    // Splice in a node containing the new element
    pred.next = new Node(e, pred.next);
    System.out.println(toString());

3 个答案:

答案 0 :(得分:0)

在添加之前,第一个元素是“1”,最后一个元素是“6” 添加后,第一个元素为“1”,最后一个元素为“6” 你是对的,第一个最后不会改变 - 他们不需要,因为你没有改变第一个或最后一个元素。

答案 1 :(得分:0)

我认为你对这个链表实现的工作方式感到困惑。存在firstlast指针以跟踪列表的开始和结束。因此,当您在列表中间插入元素时,这些指针不会更新,也不需要进行此类更新。但是如果在当前头部之前或在列表的当前尾部之后插入陆地,它们会更新。以下是处理头部插入的代码:

if (index == 0) {
    // New element goes at beginning
    first = new Node(e, first);
    System.out.println("ran");
    if (last == null)
        last = first;
    return;
}

这里的关键线实际上就是这样:

first = new Node(e, first);

first指针被分配给一个新节点,该新节点又指向 first节点。同样,如果新节点的插入位于列表的末尾,则以下代码将处理:

if (pred.next.next == null) {
    System.out.println("ran");
    last = pred.next;
}

此处last指针分配给旧last后插入的新节点。

但除了这两个边缘情况之外,无需使用插入更新firstlast

答案 2 :(得分:0)

如果索引为0,则在beginnng中添加节点,for循环不起作用。 如果为1,则循环不再执行,并且仅将节点添加到列表中。 然而,如果它是其他东西,那么直到达到index-1位置,循环将每个元素向后移动一步。然后,循环外部的代码(在包含新元素的节点中的切片)在索引处插入元素。 如果循环执行后,索引结果是最后一个,那么最后一个节点就会更新。

希望这有帮助!