【发布时间】:2014-10-15 13:05:27
【问题描述】:
我正在尝试编写一个 subList 方法,该方法返回一个包含当前对象列表的列表,包括索引 fromIndex 和 toIndex 之间。
例如,如果我的列表包含
3 5 7 9 11 20 23
我打电话给subList(0,3),我应该得到一个新的列表
3 5 7 9
返回。
我正在使用辅助方法来协助编写方法。我编写此方法的逻辑是,我将头节点分配为索引fromIndex 处的节点,同时将列表中的最后一个节点分配给索引toIndex 处的节点,但没有返回任何内容。任何帮助表示赞赏!
编辑:我创建了一个将节点添加到列表的添加方法。我仍在尝试编写自己的 subList 方法来工作。
EDIT2:我更新了一些代码,可以在底部看到(忽略上面的旧代码)。 fromIndex 和 toIndex 包含在新的子列表中。
private class Node<N extends Comparable<N>> {
private N data;
private Node<N> next;
}
private Node<L> head;
public List() {
head=null;
}
public void add(Node<L> node) {
Node<L> add = new Node<L>();
add.data = node.data;
add.next = null;
getFinal().next = add;
}
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 {
List<L> n=new List<L>();
Node<L> tail= new Node<L>();
n.head=nthItem(fromIndex);
tail=n.getFinal();
tail=nthItem(toIndex);
return n;
}
public Node<L> nthItem(int index) {
if (index < 0 || index >= size())
throw new IndexOutOfBoundsException();
Node<L> ptr = head;
int i = 0;
while (ptr != null) {
if (i == index) return ptr;
i++;
ptr = ptr.next;
}
throw new IndexOutOfBoundsException();
}
更新代码
private void add(Node<L> node) {
if(head==null){
head=node;
} else {
getFinal().next = node;
}
}
public List<L> subList(int fromIndex, int toIndex)
throws IndexOutOfBoundsException {
if(fromIndex<0 || fromIndex>size()-1 || toIndex<0 || toIndex>size()-1){ //size() is 1 bigger than max index so I subtract 1 from size() to equal them out
throw new IndexOutOfBoundsException();
}
List<L> n=new List<L>();
Node<L> startNode = head;
int counter=0;
while(startNode!=null){
if(counter>=fromIndex && counter<=toIndex){ //fromIndex and toIndex are inclusive so I've added the equals to them. However, it enters an infinite loop, which I do not understand why.
n.add(startNode);
}
startNode=startNode.next;
counter++;
}
return n;
}
【问题讨论】:
标签: java linked-list nodes sublist