I need to implement a circular single-linked list data structure. What I'm having trouble understanding is when and where do I have to state that the final node of the list must point to the first node. I have the following empty constructor to build the list:
public class SList<E> implements IList<E> {
protected SNode<E> firstNode = null;
public SList() {
firstNode = null;
}
So basically each list starts with a null object that points to null again, signifying the end of the list:
public class SNode<E> {
E elem;
public SNode<E> nextNode = null;
...
What I am unaware of however is how to make it so that when the list contains at least one node, that node will point to the first node of the list.
For example, taking a look at this addLast() method that I implemented for my regular linked list:
public void addLast(E newElem) {
SNode<E> newNode= new SNode<E>(newElem);
SNode<E> nodeTraveler = firstNode;
while (nodeTraveler.nextNode != null) {
nodeTraveler= nodeTraveler.nextNode;
}
nodeTraveler.nextNode = newNode;
}
I would have to change it into something like:
public void addLast(E newElem) {
SNode<E> nodeTraveler = firstNode;
SNode<E> newNode = new SNode<E>(newElem);
while (nodeTraveler.nextNode != firstNode){
nodeTraveler = nodeTraveler.nextNode;
}
nodeTraveler.nextNode = newNode;
newNode.nextNode = firstNode;
}
nodeTraveler would stop traversing the list once it's next node matched that of the firstNode (meaning it's at the last position), and then it would change its nextNode to the one we want to add, newNode, and point newNode to the firstNode.
Theoretically, that should work, but since I'm never actually pointing the last element to the first one prior to this method (which is my main question, how to point the last element to the first one by default), I get a nullPointer exception when the code reaches the while iteration.
Any help would be appreciated, thanks.