My teacher wants us to create a linked list class from scratch and one part of that is writing a constructor that takes a generic arraylist and turns it into a linked list and I'm having trouble with it.
Here's the code I have so far:
public LinkedList(ArrayList<E> list)
{
//If the list is null or initialized but empty, set head = null and size = 0.
head = null;
size = 0;
if (list != null && !list.isEmpty())
{
//Creating a new Node manually to set the head pointer to.
head = new Node<E>(list.get(0));
//The current Node is for iterating through the list.
Node<E> current = head;
for (int i = 0; i < list.size(); i++)
{
//Creating a new Node that the current Node points to then making current point to the next Node.
current.next = new Node<E>(list.get(i));
current = current.next;
}
size = list.size();
}
}
When I test it with an array of integers, say [1, 2, 3], the code will create a linked list containing [1, 1, 2] and I can't figure out why.
I would suggest reusing
add()method if you have one: