0

I found this code in a test and it is ok.

public class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

but Being a beginner, I have a conceptual doubt. What is the use of a class type object as member/instance variable in the same class? Something like this :

ListNode next;

can any one explain it to me ?

marko
  • 25
  • 6

1 Answers1

1

The code you have posted is the implementation of a linked list. The way the nodes of the linked list work is each node in the list contains its data (in your case: int val) and also a reference to the next node in the list. Then the again, the next node will contain a reference to its next node. This goes on until the last element of the list, for which the next node is null.

This allows each element/node of the linked list (ListNode object) to be stored at random locations unlike arrays where elements are stored one after the other in consecutive memory locations.

So you would use your ListNode class like this:

ListNode last  = new ListNode(3);
ListNode second = new ListNode(2, last);
ListNode first = new ListNode(1, second);

The three objects above may be stored at different memory locations not necessarily consecutive to each other. But it does not matter because you can access the next element of the list using the next instance variable:

ListNode second = first.next;
ListNode last = first.next.next;
//OR
ListNode last = second.next

However, in Java, you would usually not access an instance variable directly, you would use a getter and setter:

public class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    public ListNode getNext() { return next; }
    public ListNode setNext(ListNode next) { this.next = next; }
    public int getVal() { return val; }
}

Now, creating the list is much easier:

ListNode first = new ListNode(1);
ListNode second = new ListNode(2);
ListNode third = new ListNode(3);
first.setNext(second);
second.setNext(third);

// Now you could traverse the list and print the elements as follows:
ListNode element = first;
while(element != null) {
    System.out.println(element.getVal())
    element = element.getNext();
} 

Output Let me know if you still have anything that is unclear.

Amal K
  • 4,359
  • 2
  • 22
  • 44