2013-09-23 50 views
1

它只是不工作): 這裏是我的toString()方法。toString()for DoublyLinkedList

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

它告訴我那裏 「下一步= 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

您應該執行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) { 

}