在底部的我的main方法中尝试测试空的DoublyLinkedList时,底部的toString()方法给我上述错误。我的直觉告诉我,这可能是由于我正在实现的List接口引起的,因为单词“ List”在红色显示“类型已定义列表”中带有下划线,并且从该接口中提取了isEmpty()方法。虽然不完全确定。希望这对任何人都不构成负担。提前致谢。
public class DoublyLinkedList<T> implements List<T> {
/**
* Node is a pair containing a data field and a pointers to
* the previous and next nodes in the list.
*/
class Node {
T data;
Node next, prev;
Node(T data) {
this(data, null, null);
}
Node(T data, Node prev, Node next) {
this.data = data;
this.prev = prev;
this.next = next;
}
}
Node head; // always points to the headnode for this list
int n; // the number of nodes in this list, initially 0
/**
* Creates the empty list.
*/
public DoublyLinkedList() {
// TODO: Create the headnode.
// Note that the prev and next fields in the headnode should
// point back to the headnode.
Node head = new Node(null);
head.prev=head;
head.next=head;
}
public String toString() {
System.out.println("meeee");
if (this.isEmpty())
return "()";
Iterator<T> it = iterator();
StringBuilder ans = new StringBuilder("(").append(it.next());
while (it.hasNext())
ans.append(" ").append(it.next());
return ans.append(")").toString();
}
public static void main(String... args) {
DoublyLinkedList<Integer> xs = new DoublyLinkedList<>();
System.out.println(xs.toString());
}
interface List<T> extends Iterable<T> {
void add(T x); // simple add
T remove(int i);
T get(int i);
boolean contains(T x);
int size();
default boolean isEmpty() {
return size() == 0;
}
}