我正在处理一个在链接列表中添加和删除内容的类。我现在已经调试了大约一个小时,一切看起来都运行良好,但仍然没有得到正确的输出。我的方法是:
/ IMPLEMENT -- adds a book to the end of the linked list
public void add(Book b) {
BookNode curr = head;
// BookNode curr = head;
if (head == null) {
BookNode book = new BookNode(b);
head = book;
size++;
} else {
for (; curr.getNext() != null; curr = curr) {
curr = curr.getNext();
}
BookNode book1 = new BookNode(b);
curr.setNext(book1);
size++;
}
}
// IMPLEMENT -- adds a book at the specific index, or at the end if index is
// greater than size
public void add(Book b, int index) {
BookNode curr = head;
if(head == null){
BookNode book = new BookNode(b);
head = book;
size++;
}
if (index > size) {
for (; curr.getNext() != null; curr = curr) {
curr = curr.getNext();
}
BookNode book1 = new BookNode(b);
curr.setNext(book1);
size++;
}
if (index == 0) {
head = new BookNode(b, head);
} else {
for (int i = 0; i < index - 1; i++) {
curr = curr.getNext();
}
curr.setNext(new BookNode(b, curr.getNext()));
}
size++;
}
// IMPLEMENT -- removes a book and returns it, or returns null if it is not
// present
public Book remove(Book b) {
if (head == null) {
return null;
}
if (head.getBook().equals(b)) {
BookNode r = head;
head = head.getNext();
size--;
return r.getBook();
} else {
BookNode curr = head;
for (; curr.getNext() != null; curr = curr.getNext()) {
// curr = curr.getNext();
if (curr.getNext().getBook().equals(b)) {
BookNode a;
a = curr.getNext();
curr.setNext(curr.getNext().getNext());
size--;
return a.getBook();
}
}
}
return null;
}
// IMPLEMENT -- removes a book at a specific indexand returns it,
// or returns null if it is not present
public Book remove(int index) {
BookNode b;
if (index < 0 || index >= size) {
return null;
}
if (index == 0) {
// head = head.getNext(); // first return
b = head;
head = head.getNext();
size--;
return b.getBook();
} else {
BookNode curr = head;
for (int i = 0; i < index; i++) {
curr = curr.getNext(); // removes from list index
}
b = curr;
curr.setNext(curr.getNext().getNext());
size--;
return b.getBook();
}
}
所以所有的方法都在运行和工作,但是一旦它删除了一本书然后查找它就不会像它应该的那样返回null。而且在将列表添加到列表末尾时也遇到了问题。我把它缩小了,看起来我的删除方法(索引)出了问题。