I am writing a linked list in Java. Below is the code:
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
}
}
}
I implemented the add method in a recursive way. When I try to add an element to the list, I failed. I tracked the problem which is after the add_aux(newList.head, element) -- the newList.head is still null.
Node newNode = new Node(element, null);
node = newNode;
This is because you are assigning a reference to a node
variable which is local to the method and you are assuming that it will be reflected into the newList.head
.
One way is you always return the node
and assigning it to newList.head
. That way, it will have the start of the list. So your method definition will be like:
private Node add_aux(Node node, T element) {
.... // all the code is same.
return node; // add this in the end.
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.