在索引(LinkedList)上插入对象的方法



我正在尝试创建一个方法,将另一个对象从我的链表中替换为特定对象。replaceAtIndex(对象、索引)。我不知道如何从我的链表中获得指定的索引。

下面是我的链表类的代码:
public class CellList {
public class cellNode{
private cellPhone phone;
private cellNode next;

//default null
public cellNode() {
phone = null;
next = null;
}

//parametrized 
public cellNode(cellPhone phone, cellNode next) {
this.phone = phone;
this.next = next;
}

public cellNode(cellNode x) {
this.phone = x.phone;
this.next = x.next;
}

//Cloning
protected Object clone() throws CloneNotSupportedException {
cellNode x=new cellNode(this.phone,this.next);
return x;
}
public cellPhone getPhone() {
return phone;
}
public cellNode getNext() {
return next;
}
public void setPhone(cellPhone phone) {
this.phone = phone;
}
public void setNext(cellNode next) {
this.next = next;
}

}
private cellNode head;
private int size;

//default
public CellList() {
head=null;
size=0;
}
//copy
public CellList(CellList c) {
this.head = c.head;
this.size = c.size;
}

//Add a node at start
public void addToStart(cellPhone c) {
cellNode cn=new cellNode(c,head);
head=cn;
size++;
}

我尝试了这个方法,但它只有在索引传递小于1时才能正确地替换我的元素。例如,如果我尝试索引3,它根本不会替换任何东西,而是显示正常的列表。如果我尝试一个比我的大小大的索引,它会像预期的那样抛出异常。

public void insertAtIndex(cellPhone c,int index) {
if(index<0 || index>=size) {
throw new NoSuchElementException("Out of boundary!!!");
}
else {
if(index==0) {
addToStart(c);
}
else if(index>0 && index<size) {
cellNode curr=head.next;
cellNode prev=head;
cellNode cn=new cellNode(c,head);
int i=1;
while(curr!=null) {
if(i==index) {
prev.next=cn;
cn.next=curr;
size++;
i++;
return;
}
prev=curr;
curr=curr.next;
}
}
}
}

不要在while (curr != null)循环中更改i。如果你添加i++,它看起来应该工作。

最新更新