要使代码不报错并且不添加其他方法,您可以尝试以下更改:
- 在DoublyList类的构造函数中,将this.head.prev和this.head.next设置为null。
public DoublyList() {
this.head = new DoubleNode<T>();
this.head.prev = null;
this.head.next = null;
}
- 在toString方法中,如果列表为空,则返回一个空字符串。
public String toString() {
if (isEmpty()) {
return "";
}
String str = this.getClass().getName() + "(";
DoubleNode<T> p = this.head.next;
while (p != null) {
str += p.data.toString() + ((p.next != null) ? "," : "");
p = p.next;
}
return str + ")";
}
通过以上修改,您应该能够让代码不报错。
内容由零声教学AI助手提供,问题来源于学员提问




