Nodes


Collapse 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

  • I don't understand the class definition. What does the line

    Node next;

    mean?

  • Node 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).

  • Thanks. I'll think about that...

Contact Us
Sign in or email us at [email protected]