public void insertIt (Node firstNode, Node newNode) {
firstNode.next = newNode;
newNode.next = null;
}
I couldn’t find the class that uses .next, can anyone show me? Also, I don’t really understand this. I’m setting firstNode.next=newNode, so how would firstNode include firstNode.next? I hope that makes sense.
From my notes:
> Example 1 to practice with links:
> Node node1 = new Node(22); Node node2
> = new Node(44); firstNode = node1; node1.next = node2; node2.next = null;
> Produces:
> firstNode -> 22 -> 44 -> null So firstNode.data is 22 and
> firstNode.next.data is 44. Since
> firstNode.next.next is null, a
> reference to firstNode.next.next.data
> is an error.
>
> Example 2 to practice with links: What
> is node3.data ?
> node3 -> 99 -> null
> Answer: 99
>
> Example 3 to practice with links:
> public void insertIt (Node firstNode,
> Node newNode) {
> firstNode.next = newNode;
> newNode.next = null; }
Edit: What happens if you assign a node to another node?
For example, head -> 2 -> 3 -> null
node1 = node2;
What is changing? Is node1s value 3? or is it changing its reference/pointer?
After seeing your comment, I think I understand what you’re attempting to do. This code is from an implementation of a LinkedList Data Structure. You should read the wikipedia article, but in short, a linked list is made up of
Nodesthat contain adataelement along with a pointer to the next element in the list. Because of this, it is possible to traverse the list in order with knowledge of only the first element. The.nextis used to access the next data member relative to the current node. When you insert an element, you usually need to do something like this:This method inserts the
NodenewNodeafter theNodenodeBeforeso that when you traverse the list, after you reachnodeBeforeyou reachnewNode. Typically, the end of the list of signified by anullpointer.Edit To address your comment, the class
Nodelikely looks like this:That is where
nextcomes from. It’s a public data member of theNodeclass