从双向链表中删除游标
Removing cursor from a doubly linked list
我正在尝试从列表中删除游标并使其引用前一个 CarListNode(或头部,如果游标先前引用了列表的头部)。同时仍然返回游标内的信息。
我的代码没有正确删除光标。我的代码有什么问题?
这是我当前的代码:
public Fruit removeCursor() throws EndOfListException {
if (cursor == null) {
throw new EndOfListException();
} else if (cursor.getPrev() == null) {
head = cursor.getNext();
cursor.setNext(null);
cursor.setPrev(null);
cursor = head;
} else if (cursor.getNext() == null) {
tail = cursor.getPrev();
cursor.setPrev(null);
cursor.setNext(null);
cursor = tail;
} else {
cursor.setData(cursor.getNext().getData()); //this isn't a singly linked list
cursor.setNext(cursor.getNext().getNext());
}
count--;
return cursor.getData();
}
您的 else
子句不 "remove the cursor"...
尝试这样的事情:
else {
cursor.getPrev().setNext(cursor.getNext());
cursor.getNext().setPrev(cursor.getPrev());
// You might want to release the cursor's item, EG:
cursor = null;
cursor = cursor.getNext();
}
我正在尝试从列表中删除游标并使其引用前一个 CarListNode(或头部,如果游标先前引用了列表的头部)。同时仍然返回游标内的信息。 我的代码没有正确删除光标。我的代码有什么问题?
这是我当前的代码:
public Fruit removeCursor() throws EndOfListException {
if (cursor == null) {
throw new EndOfListException();
} else if (cursor.getPrev() == null) {
head = cursor.getNext();
cursor.setNext(null);
cursor.setPrev(null);
cursor = head;
} else if (cursor.getNext() == null) {
tail = cursor.getPrev();
cursor.setPrev(null);
cursor.setNext(null);
cursor = tail;
} else {
cursor.setData(cursor.getNext().getData()); //this isn't a singly linked list
cursor.setNext(cursor.getNext().getNext());
}
count--;
return cursor.getData();
}
您的 else
子句不 "remove the cursor"...
尝试这样的事情:
else {
cursor.getPrev().setNext(cursor.getNext());
cursor.getNext().setPrev(cursor.getPrev());
// You might want to release the cursor's item, EG:
cursor = null;
cursor = cursor.getNext();
}