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();
.
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.
See more on this question at Stackoverflow