Nodes
Collapse Content
Show Content
We'll start with a really simple data structure. A Node is simple element that holds data and a pointer to another node. Here's a simple Java implementation of a Node:
class Node{
int data;
Node next;
public Node(int d){
data = d;
}
}
Nodes are very simple, but form the basis of many data structures. We're about to use them in Lists, and later you can see how they're used in Trees.
Challenge
Given the above Node class, what will the following code print?
public class Main {
public static void main(String[] args) {
Node a = new Node(1);
Node b = new Node(2);
Node c = new Node(3);
a.next = b;
b.next = c;
System.out.println(a.next.next.data);
}
}
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.
Comments
Bolke
Aug 1, 2:47 PMI don't understand the class definition. What does the line
Node next;
mean?
Learneroo
Aug 2, 12:10 AMNode is the name of the class (like Car or String). Each Node points to another Node called 'next' (though it could be called anything else as well).
Bolke
Aug 2, 9:22 AMThanks. I'll think about that...
Ryan Vergara
Nov 2, 7:19 AMIn JavaScript we can implement a Node as follows (highly similar in form as the one in the lesson):
class Node {
constructor(data){
this.data = data;
}
}
let a = new Node("A");
let b = new Node("B");
let c = new Node("C");
a.next = b;
b.next = c;
console.log(a.next.next.data) //will print out "C"
Notorious
Oct 15, 11:03 AMA better implementation of the Node class.
class Node
{
private E element;
private Node next;
public Node(E element, Node next)
}