Reputation: 17
I have an append method for my linked list where I want to add to the tail, however when a new node is added to the list, headNode and tailNode both become the newly inserted node. How do I keep headNode to stay as the first node that was entered into the list and not have it become the same thing as tailNode.
public static void append()
{
for(int x = 0; x < gradeArray.length; x++)
{
if(gradeArray[x] < 70)
{
StudentNode newNode = new StudentNode(nameArray[x], gradeArray[x], null);
if(headNode == null)
{
headNode = newNode;
}
else
{
tailNode.nextNode = newNode;
}
tailNode = newNode;
}
}
}
Upvotes: 0
Views: 589
Reputation: 6006
I am not sure what mistake are you doing but see below this code is working perfectly fine.
public class Grades {
public static String[] nameArray = new String[50];
public static int[] gradeArray = new int[50];
public static StudentNode headNode;
public static StudentNode tailNode;
public static void append() {
for (int x = 0; x < gradeArray.length; x++) {
if (gradeArray[x] < 70) {
String name = nameArray[x];
int grade = gradeArray[x];
StudentNode newNode = new StudentNode(name, grade, null);
if (headNode == null) {
headNode = newNode;
} else {
tailNode.nextNode = newNode;
}
tailNode = newNode;
}
}
}
public static void main(String[] args) throws java.lang.Exception {
for (int i = 0; i < 50; i++) {
nameArray[i] = "name-" + i;
gradeArray[i] = i;
}
append();
for(int i=0; i<50; i++) {
nameArray[i] = "name-" + (i + 50);
gradeArray[i] = i + 50;
}
append();
System.out.println(headNode.toString());
System.out.println(tailNode.toString());
}
}
class StudentNode {
public int grade;
public String name;
public StudentNode nextNode;
public StudentNode(String n, int g, StudentNode sn) {
name = n;
grade = g;
nextNode = sn;
}
public String toString() {
return name + ", " + grade;
}
}
Even if you change grade and name arrays and run append again it still keeps the head correct.
Upvotes: 1
Reputation: 831
Why did you append this statement ? tailNode = newNode;
Imagine, thread goes through by if(headNode == null)
he assign newNode adress to headNode . After that, tailNode = newNode;
is executed and tail pointing to newNode.
Finally, tailNode and headNode point to the same object : newNode.
I think you have to delete this statement tailNode = newNode;
Upvotes: 0