Joe Pak
Joe Pak

Reputation: 173

Adding a node to beginning of a list in Java?

I'm learning linked list basics via Sedgewick's Algorithms and came across adding nodes to the beginning of a linked list. I've noticed they're redefining the "first node" using the code below:

Node firstNode = new Node();
Node secondNode = new Node();
Node thirdNode = new Node();

//create 3 initial nodes
firstNode.item = "to";
secondNode.item = "be";
thirdNode.item = "or";

//set order of nodes
firstNode.next = secondNode;
secondNode.next = thirdNode;

//add new node to beginning
Node oldFirstNode = firstNode;

//recreate first node
firstNode = new Node();

firstNode.item = "not";
firstNode.next = oldFirstNode;

Why do we not do: Node firstNode = new Node();? Not understanding why it's instead firstNode = new Node();.

Upvotes: 0

Views: 571

Answers (2)

Mureinik
Mureinik

Reputation: 311188

The first time you assign to firstNode is when you define it:

Node firstNode = new Node();

Once it's defined, you already have a variable named firstNode, so you mustn't redefine it, just assign a new value to it - in this case, a newly created Node:

firstNode = new Node();

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500365

You couldn't have

Node firstNode = new Node();

later on in the code - because that would be trying to declare a new local variable with the same name as an existing one. (You can have a local variable with the same name as an instance field or a static field, but you can't have two local variables with the same name in scope at the same time.) Instead, this line:

firstNode = new Node();

assigns a new value to the existing local variable.

Upvotes: 3

Related Questions