1 回答
TA贡献1765条经验 获得超5个赞
我添加了评论,以及一些修复:
public boolean addItem(ListItem newItem) {
if(this.root == null){
this.root = newItem;
return true;
}
ListItem currentItem = this.root;
while (currentItem != null){
int comparison = currentItem.compareTo(newItem);
if (comparison < 0){ // if cur < new
newItem.setPrevious(currentItem.previous()); // advance cur
if (currentItem.next()!=null){
currentItem = currentItem.next();
} else { // if end list
currentItem.setNext(newItem); // append new
newItem.setPrevious(currentItem);
return true;
}
} else if (comparison > 0){
// new < cur, insert before, fixes made to this part
newItem.setNext(currentItem); // set new.nxt
newItem.setPrevious(currentItem.previous()); // set new.prv
if (newItem.previous()!= null){ // if new.prv != 0
newItem.previous().setNext(newItem); // set new.prv.nxt
else // else
this.root = newItem; // set root
currentItem.setPrevious(newItem); // set cur.prv
return true;
}
return false; // return false if duplicate
}
}
使用文本图形。假设新节点 N 将插入到 A 之后和 B 之前。初始状态,cur (currentItem) = B:
cur == B
A <------ B 0 <- N cur.prv == A new.prv = 0
A ------> B N -> 0 cur.prv.nxt == B new.nxt = 0
顺序是:
N -> B new.nxt = cur
A <- N new.prv = cur.prv
A -> N new.prv.nxt = new
N <- B cur.prv = new
导致
A -> N -> B
A <- N <- B
添加回答
举报