【发布时间】:2017-12-13 05:31:11
【问题描述】:
以下代码来自 java LinkedList 实现。该方法在列表的索引点添加一个字符串元素,取自我的一本 cs 书籍。
链表类有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"],但是查看add方法的代码我不知道first或last 节点指针得到更新。因为在我看来,这些是唯一运行的代码,因为索引不是 0 并且最后一个不会改变
编辑
对象节点first在toString方法(未显示)中用于遍历集合
// 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());
【问题讨论】:
-
只是为了清楚我已经测试了这个添加方法并且它确实有效。
标签: java pointers linked-list