0

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();.

1
  • 2
    I'm not sure what you mean. Both lines are present in the code you posted. Commented Jul 4, 2015 at 19:41

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.