【发布时间】:2014-10-15 22:47:47
【问题描述】:
我正在尝试编写一个 subList 方法,该方法返回一个包含当前对象列表的列表,包括索引 fromIndex 和 toIndex 之间。
例如,如果我的列表包含
9 11 20 23 28 30
我打电话给subList(1,4),我应该得到一个新的列表
11 20 23 28
返回。
对于我的 subList() 方法,我尝试运行它,但最终进入了无限循环。当下一个节点为空时,它应该退出循环但没有发生,所以我需要帮助弄清楚为什么会发生这个无限循环以及我能做些什么。任何帮助表示赞赏!
private class Node<N extends Comparable<N>> {
private N data;
private Node<N> next;
}
private Node<L> head;
public List() {
head = null;
}
private void add(Node<L> node) {
if(head == null) {
head=node;
} else {
getFinal().next = node;
}
}
public Node<L> getFinal(){
Node<L> node = head;
while (node.next != null) {
node = node.next;
}
return node;
}
public int size() {
if (head == null) return 0;
int counter = 0;
for (Node<L> curr = head; curr != null; curr = curr.next)
counter++;
return counter;
}
public List<L> subList(int fromIndex, int toIndex) throws IndexOutOfBoundsException {
if(fromIndex < 0 || fromIndex > size()-1 || toIndex < 0 || toIndex > size()-1) {
throw new IndexOutOfBoundsException();
}
List<L> n = new List<L>();
Node<L> startNode = head;
int counter = 0;
while(startNode != null) {
if(counter >= fromIndex && counter <= toIndex) { //infinite loop happens here
n.add(startNode);
}
startNode=startNode.next;
counter++;
}
return n;
}
【问题讨论】:
-
您似乎缺少类声明,某些方法不在类中。
-
您没有显示您在哪里创建代码并将值分配给您的列表。您确定没有将节点添加到列表中,而该列表中的
next字段已设置为列表中的其他内容吗?
标签: java linked-list nodes sublist