Question about Java Nodes, specifically with .next
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.nex开发者_运维知识库t = 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 node1
s 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 Nodes
that contain a data
element 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 .next
is 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:
public void insertNode(Node nodeBefore, Node newNode){
newNode.next = nodeBefore.next;
nodeBefore.next = newNode;
}
This method inserts the Node
newNode
after the Node
nodeBefore
so that when you traverse the list, after you reach nodeBefore
you reach newNode
. Typically, the end of the list of signified by a null
pointer.
Edit To address your comment, the class Node
likely looks like this:
public class Node{
public Node next;
public Object data;
}
That is where next
comes from. It's a public data member of the Node
class
It looks like you are learning about linked lists... this method essentially adds another node to the end like this:
firstNode newNode
+------+------+ +------+------+
| data | next-|--->| data | null |
+------+------+ +------+------+
精彩评论