gpt4 book ai didi

java - DoublyLinkedList 的 toString()

转载 作者:行者123 更新时间:2023-11-30 11:28:12 24 4
gpt4 key购买 nike

它只是不起作用 ):这是我的 toString() 方法。

public String toString() {
String s= "[";
DoublyLinkedList<E>.ListNode next= new ListNode(null,null,null);
next= head.successor();

while(next!=tail){
s+= next.getValue()+ ", ";
next=next.successor();

}
s +="]";
// Write this method body and remove this comment
return s;
}

它告诉我在“next= head.successor()”有一个空指针错误

这是 ListNode 类:

 /** An instance is a node of this list. */
public class ListNode {
/** Predecessor of this node on the list (null if the list is empty). */
private ListNode pred;

/** The value of this node. */
private E value;

/** Successor of this node on the list. (null if the list is empty). */
private ListNode succ;

/** Constructor: an instance with predecessor p (p can be null),
* successor s (s can be null), and value v. */
private ListNode(ListNode p, ListNode s, E v) {
pred= p;
succ= s;
value= v;
}

/** Return the value of this node. */
public E getValue() {
return value;
}

/** Return the predecessor of this node in the list (null if this node
* is the first node of this list). */
public ListNode predecessor() {
return pred;
}

/** Return the successor of this node in the list (null if this node
* is the last node of this list). */
public ListNode successor() {
return succ;
}

和双链表...

    /** An instance is a doubly linked list. */
public class DoublyLinkedList<E> {
private ListNode head; // first node of linked list (null if none)
private ListNode tail; // last node of linked list (null if none)

private int size; // Number of values in linked list.

/** Constructor: an empty linked list. */
public DoublyLinkedList() {
}

/** Return the number of values in this list. */
public int size() {
return size;
}

/** Return the first node of the list (null if the list is empty). */
public ListNode getHead() {
return head;
}

/** Return the last node of the list (null if the list is empty). */
public ListNode getTail() {
return tail;
}

/** Return the value of node e of this list.
* Precondition: e must be a node of this list; it may not be null. */
public E valueOf(ListNode e) {
return e.value;
}

最佳答案

你应该实现 Iterable为您的 list 。

public class DoublyLinkedList<E> implements Iterable<E> {
...

public Iterator<E> iterator() {
// TODO: return a new iterator here.
}
}

然后执行一个Iterator<E>作为内部类的列表。有关示例,请参见 Java 源代码:

这是循环访问列表的成熟模式。然后,您不必担心会收到 while。向右循环,相反,您可以只使用标准 for每个循环:

for (E item: this) {

}

关于java - DoublyLinkedList 的 toString(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18965591/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com