【问题标题】:Remove method for linkedList implementation in Java删除 Java 中的linkedList 实现的方法
【发布时间】:2014-01-06 04:56:58
【问题描述】:

我在specified index 的关于从linkedList 中删除元素的讲座中获得了这种方法。 我了解该方法的工作原理,但我不明白为什么 for-loop 在所需索引之前留下了 current node pointer 两个索引。

方法如下:

public void remove(int index) {
        if (index == 0) {
            // removing the first element must be handled specially
            front = front.next;
        } else {
            // removing some element further down in the list;
            // traverse to the node before the one we want to remove
            ListNode current = front;
            for (int i = 0; i < index - 1; i++) {
                current = current.next;
            }

            // change its next pointer to skip past the offending node
            current.next = current.next.next;
        }
    }

for-loop 来自0 to &lt; index-1,而我认为它应该来自0 to &lt; index。这样,指针就位于需要删除的index 前一个index。但是,上述方法效果很好。

例如: 在下面LinkedList

让我们考虑删除Node C。通过上述循环构造,current pointer 将指向Node Acurrent.next 将指向Node Bcurrent.next.next 将是 Node C。执行current.next=current.next.next 将导致Node B 删除而不是Node C

我觉得我的理解有问题,谁能解释一下?

【问题讨论】:

    标签: java pointers methods linked-list


    【解决方案1】:

    for循环从0到

    在您的示例中,删除 C 意味着索引为 2。所以i 只去0,因为1 不是&lt; 1

    currentA 开始,for 循环一次,current 转到B

    currentB,所以current.next.nextD,这有效地删除了C

    【讨论】:

      猜你喜欢
      • 2012-11-15
      • 1970-01-01
      • 1970-01-01
      • 2019-12-15
      • 1970-01-01
      • 2016-12-12
      • 2021-09-18
      • 1970-01-01
      • 2020-09-21
      相关资源
      最近更新 更多