DoublyLinkedList的toString()

时间:2013-09-23 17:45:29

标签: java doubly-linked-list

它只是不起作用): 这是我的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;
    }

和DoublyLinkedList ...

    /** 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;
    }

1 个答案:

答案 0 :(得分:1)

您应该为列表实施Iterable

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) {

}
相关问题