Reputation: 17
I have a linked list class and a node class, and I want to write a constructor that will fill a linked list with the same node up to size 'n'. However, I can't seem to formulate the logic properly. Here's where I'm at:
I have the field 'head' to represent the head of the linked list.
The 'node' class has a field to represent the next value (Consider: node.next).
public LinkedList(int size, Object value)
{
int index = 0;
head = value; //setting first node to value
Object workingReference = head; //creating a working reference to iterate through the list
for(index = 0; index < size - 1; index++)
{
workingReference.next = value; //setting the next node to the given value
workingReference = workingReference.next; //setting the "index" to the next "index"
}
}
The problem is that there is never a "null" value to when the loop hits the constraints, so the next node is always the given "value", making the list "infinite". I've played with setting value.next to null, but that sets head.next to null for some reason. I feel that the solution is right in front of me, but I'm not thinking about it the right way. Thank you for your time.
Upvotes: 0
Views: 274
Reputation: 60438
To start with, change the type of value
and workingReference
to Node
instead of Object
just to help everyone understand.
Your main problem is that you're not copying value
when you're assigning it. What you probably want is the value
variable's value, which is why calling it a Node
instead of an Object
is so helpful here.
public LinkedList(int size, Node value)
{
int index = 0;
head = value;
Node workingReference = head;
for(index = 0; index < size - 1; index++)
{
// Here, workingReference, head and value are all the same thing
// So when you set workingReference.next = value,
// You've created a loop (value.next points to value)
workingReference.next = value;
workingReference = workingReference.next;
}
}
What you want to do is create a new node each time, with the contents of the value
node. Let's rename value
to initialNode
to make it clearer how the fix works:
public LinkedList(int size, Node initialNode)
{
int index = 0;
head = initialNode;
Node workingReference = head;
for(index = 0; index < size - 1; index++)
{
Node newNode = new Node(initialNode.value);
workingReference.next = newNode;
workingReference = workingReference.next;
}
}
Now, instead of having created a loop, each node is new. head
points to the initialNode
, and its next
(and all next
s for size
iterations) all point to the value
field of that initialNode
.
If you want the value Object to be the thing that's passed to the method, do it like this:
public LinkedList(int size, Object initialValue)
{
int index = 0;
head = new Node(initialValue);
Node workingReference = head;
for(index = 0; index < size - 1; index++)
{
Node newNode = new Node(initialValue);
workingReference.next = newNode;
workingReference = workingReference.next;
}
}
Upvotes: 0