我对如何从列表开头或列表结尾进行搜索感到困惑。
编辑:这是代码,超过200行,因此,如果您需要其他任何内容,请询问。我添加了Node类。
返回节点号k。前提:0 <= k <列表大小。如果k为0,则返回第一个节点。如果k = 1,则返回第二个节点,...
public Node getNode(int k) {
//TODO 4. This method should take time proportional to min(k, size-k).
// For example, if k <= size/2, search from the beginning of the
// list, otherwise search from the end of the list.
if (k <= size/2) {
}else {
}
return null;
}
public class Node {
private Node prev; // Previous node on list (null if this is first node)
private E val; // The value of this element
private Node next; // Next node on list. (null if this is last node)
/** Constructor: an instance with previous node p (can be null),
* value v, and next node n (can be null). */
Node(Node p, E v, Node n) {
prev= p;
val= v;
next= n;
}
/** Return the node previous to this one (null if this is the
* first node of the list). */
public Node prev() {
return prev;
}
/** Return the value of this node. */
public E value() {
return val;
}
/** Return the next node in this list (null if this is the
* last node of this list). */
public Node next() {
return next;
}
}
}
答案 0 :(得分:0)
假设您实际上需要搜索列表,而不只是返回myNodeList.get(k)
,然后请参见下文:
看看正常循环:
for (int index=0; index < size; index++) {
//do something
}
该循环从索引0(index=0
)开始,一旦索引大于大小(index < size
),它结束,并增加了每个循环(index++
),但我们可以轻松地对其进行修改它以最大尺寸/结束index=size-1
开始,以0(index >= 0
)结尾,并减小每个循环(index--
)。
所以从一开始:
for (int index=0; index < myNodeList.size(); index++) {
//do something
}
从结尾:
for (int index=size-1; index >= 0; index--) {
//do something
}