【发布时间】:2022-12-05 03:54:23
【问题描述】:
我正在尝试创建一种方法,用另一个对象替换链表中的特定对象。 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 replacetAtIndex(cellPhone c,int index) {
if(index<0 || index>=size) {
throw new NoSuchElementException("Out of boundary!!!");
}
else {
if(index==0) {
head.phone=c;
}
else {
cellNode curr=head;
int i=0;
while(curr!=null) {
if(i==index) {
curr.phone=c;
size++;
return;
}
curr=curr.next;
}
}
}
}
`
【问题讨论】:
标签: java object linked-list