[英]Custom LinkedList: remove method does not work as expected
我正在实现自定义LinkedList
类的remove()
方法,但它不会从列表中删除任何项目,而且我不知道为什么。
这是我的方法:
public void remove(int position) {
if (position < 0 || position >= size) {
throw new IndexOutOfBoundsException(
"position should be beween 0 and size - 1");
}
Cell current = top;
for (int i = 0; i < position; i++) {
current = current.next;
}
current = current.next.next;
size--;
}
此方法尝试删除2个节点之间的项目(忽略删除第一个节点和最后一个节点的情况)。
这是我正在执行的测试用例,尝试删除索引为2的元素后,它仍会打印孔列表:
CustomList<String> list = new CustomList<String>();
list.add("Hello");
list.add("morena");
list.add("What");
list.add("Miranda");
list.add("Aston");
list.remove(2);
list.printAll();
为了完成,这是列表的完整实现:
public class CustomList<T> {
private class Cell {
T data;
Cell next;
public Cell(T data) {
this.data = data;
}
}
private Cell top;
private int size;
public void add(T data) {
addAtEndInOn(data);
size++;
}
/**
* adds an item at the end of the list in O(n) by iterating the whole list
* before adding the node
*/
private void addAtEndInOn(T data) {
if (top == null) {
top = new Cell(data);
} else {
Cell current = top;
while (current.next != null) {
current = current.next;
}
current.next = new Cell(data);
}
}
public void remove(int position) {
if (position < 0 || position >= size) {
throw new IllegalArgumentException(
"position should be a positive number");
}
Cell current = top;
for (int i = 0; i < position; i++) {
current = current.next;
}
current = current.next.next;
size--;
}
public void printAll() {
Cell current = top;
while (current != null) {
System.out.println(current.data);
current = current.next;
}
}
}
current = current.next.next
不会更改列表中的任何内容。
为了删除一个元素,您需要编写:
current.next = current.next.next;
这将删除当前元素旁边的元素。 这不是要删除的元素,应更改for循环,以便当current是要删除的元素之前的元素时,它会停止。
确保测试current.next
不为null,以避免NullPointerException
。
您必须断开链接,而不仅仅是改变电流的位置。 该链接由current.next表示
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.