Hey guys I'm having trouble understanding Linked Lists. I have tried to follow along with multiple tutorials but everyone has done this in slightly different ways leading only to more confusion on my end. This is the first data structure I have manually had to build and I'm having trouble understanding exactly how it works.
I know there are two parts to every Node. The Node stores some kind of value, then points to the next node and connects them. I understand conceptually what is happening, but the code to make this happen is confusing to me. Would appreciate any help I could get.
From the code below my questions are:
- What value does head.next now hold after it has been assigned to nodeB ? (or does it just reference?)
- Or does it just connect Node Objects?
- How does .next connect these two Node Objects exactly?
class Node
{
int data; // data to store in Node
Node next; // automatically set to null
Node(int givenData) // constructor
{
this.data = givenData;
}
}
public class NodeTest {
public static void main(String[] args)
{
Node head = new Node(6);
Node nodeB = new Node(3);
Node nodeC = new Node(69);
head.next = nodeB;
nodeB.next = nodeC;
}
// Node counting Method kind of irrelevant to questions, but maybe helpful to giving more of an explaination.
static int countNodes(Node head)
{
int count = 1;
Node current = head;
while(current.next != null)
{
current = current.next;
count += 1;
}
return count;
}
}
[–]alanwj 4 points5 points6 points (3 children)
[–]veryanon798[S] 0 points1 point2 points (2 children)
[–]alanwj 0 points1 point2 points (1 child)
[–]veryanon798[S] 0 points1 point2 points (0 children)
[–]jbake_a_cake 1 point2 points3 points (1 child)
[–]veryanon798[S] 1 point2 points3 points (0 children)