Im screwing something up. The instance variable has been declared and initalized
ID: 3882501 • Letter: I
Question
Im screwing something up. The instance variable has been declared and initalized to "null." I've tried the debugger, but my user info is being deleted. The Singly linked list worked fine, but turning it into a doubly is causing problems -- somthing with my pointers. Below is just an add() for the singly. Requesting help with this. AND if comments about "previous/next sentinels" would be great. Thanks.
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Again: The instance variables have been declared and initalized
Add a previous element instance variable to the Element class so each element has a pointer to the next element in the list and the last element in the list. Whenever you add a new element to the list, this variable needs to be updated so it always points to the previous element in the list.
Add a lastNode instance variable to ElementList class. Modify the addElement class to update the lastNode variable so it is always pointing to the last node of the linked list.
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
public void addElement(String firstName, String lastName, String phoneNumber) {
Element newNode;
Element currentNode;
newNode = new Element(firstName, lastName, phoneNumber);
if (this.firstNode == null)
{
this.firstNode = newNode;
} else {
currentNode = this.firstNode;
while (currentNode.nextElement != null )
{
currentNode = currentNode.nextElement;
}//END WHILE
currentNode.nextElement = newNode;
}
}//END ADDELEMENT()
Explanation / Answer
-
public void addElement(String firstName, String lastName, String phoneNumber) {
Element newNode;
Element currentNode;
newNode = new Element(firstName, lastName, phoneNumber);
if (this.firstNode == null)
{
this.firstNode = newNode;
} else {
currentNode = this.firstNode;
while (currentNode.nextElement != null )
{
currentNode = currentNode.nextElement;
}//END WHILE
currentNode.nextElement = newNode;
newNode.prevElement = currentNode;
this.lastNode = newNode;
}
}//END ADDELEMENT()
//I ran this code. And it is working fine. Cheers :)