2015-10-06 124 views
-1

我正在用Java写一个链表。以下是代码:将内部类对象作为函数参数传递

public class FunctionalList<T> { 

    class Node { 
     private T data; 
     private Node next; 

     //constructor 
     public Node(T data, Node next) 
     { 
      this.data = data; 
      this.next = next; 
     } 
    } 
    private Node head; 
    /** 
    * default constructor, create an empty list 
    */ 
    public FunctionalList() { 
     head = null; 
    } 

    public FunctionalList<T> add(T element) { 
     FunctionalList<T> newList = new FunctionalList<T>(); 
     add_aux(newList.head, element); 

     return newList; 
    } 

    private void add_aux(Node node, T element) 
    { 
     if (node == null) 
     { 
      Node newNode = new Node(element, null); 
      node = newNode; 
     } 
     else if (node.next != null)  // go to the end of the list 
     { 
      add_aux(node.next, element); 
     } 
     else 
     { 
      Node newNode = new Node(element, null); // create new node 
      node.next = newNode; //add the element to the list 
     } 
    } 
} 

我以递归的方式实现了add方法。当我尝试添加一个元素到列表中时,我失败了。我跟踪了add_aux(newList.head,element)之后的问题 - newList.head仍然为空。

+0

我想你会得到一个NullPointerException,你引用newList.head,因为它从来没有初始化。 –

+0

问题应该包括具体的错误和代码来重现它。 –

回答

1
Node newNode = new Node(element, null); 
    node = newNode; 

这是因为要分配给一个变量node其是本地的方法的引用,并且您假定它会被反射到newList.head

一种方法是你总是返回node并将其分配给newList.head。这样,它就会有名单的开始。所以你的方法定义如下:

private Node add_aux(Node node, T element) { 
.... // all the code is same. 
return node; // add this in the end. 
} 
相关问题