Here is the class header along with its fields below:
public class SinglyLinkedList <E> implements MiniList <E>
{
protected Entry <E> head = null;
private int size = 0;
I need to implement this method for my lab and I’m clueless with LinkedLists:
public boolean add(E element)
{
//method should return true once element is added
//EDIT: I THINK I SOLVED IT:
head.element = element;
return true;
//Does everyone think the two lines above look correct?
}
So very simply problem and I’m very new to non-random access data structures. Could someone solve the problem above for me? I need a base foundation so I can continue with the rest of the lab.
Well, a Linked List works like this:
You have the head node, this has a reference to the next node, which has a reference to the next, etc. Here’s a diagram I just drew:
The head has a reference to the following nodes, but it also has the Data within. So if I create a Linked List of Strings.
The head has the data VEGGIES, then also has a reference to the next object in the list, in other words the FRUITS term, which is also the tail.
Let’s say our list is empty. No head, no tail, no data. This we assign our head as a new entry. It will be the first element in the list, and our doorway into accessing the list. If the list isn’t empty, in order to add to our list, we have to get access to the current last element in the list. To do that, we have to travel down the list.
That will give us the last entry. Then in order to add another element, we simply set the reference of the last object to the Entry we’re trying to add.
That’s the gist of how it works. Now you just have to implement that based upon what your “Entry” object is.