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...

  • In 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;

    cont...
  • A better implementation of the Node class.
    class Node
    {
    private E element;
    private Node next;
    public Node(E element, Node next)

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