Home > Back-end >  Singly Linked List pass by value
Singly Linked List pass by value

Time:08-19

Hi i am learning linked list in java. Its a simple doubt but couldn't figure out.

class Node{
int data;
Node next;
Node(int data){
this.data = data;
this.next = null;
}

//java main method

Node head = null;
Node newNode = new Node(1);
head.next = newNode;

Here i am passing the reference of the newNode to the next field in the Node class. The next is holding the reference of the newNode.

In dart programming languages objects are passed via call by value. By doing the above code is also working fine. My question is can we implement the Node field inside the Node class with either by reference or value.

In the context of c , I don't know much c syntax but roughly it looks like this //with pointer

class Node{
public:
int data;
Node* next;
}

It is possible to implement the above code like this one

//without pointer

class Node{
public:
int data;
Node next;
}

CodePudding user response:

As stated by the other answers, your code wont work since your head variable is null and thus would throw a NullPointerException. Your main method should like this:

Node head = new Node(0);
Node newNode = new Node(1);
head.next = newNode;

Java is always passing references by value. For a comprehensive answer see https://stackoverflow.com/a/40523/19799529

CodePudding user response:

Pass-by-value

Java is always passing by value (as you are accustomed to):

int x = 3; f(x);
Object y = new Object(); g(y);

Above neither f nor g can alter the passed variables x and y. The variables are just memory slots in which the value is stored, and that value is passed (not which memory slot), whether primitive type (int) or class instance (Object).

Linked list

Your Node class is fine.

public class SingleLinkedList {
    Node head;
    int count;

    public int size() {
        return count;
    }

It is worth holding the Node inside a list class, possibly with a field for the number of elements. You could use that for index checking.

    public void add(int i, int data) {
        head = addToNodes(head, i, data);
          count;
    }

    private Node addToNodes(Node link, int i, int data) {
        if (i <= 0 || link == null) {
            Node node = new Node(data);
            node.next = link;
            return node;
        }
        link.next = addToNodes(link.next, i - 1, data);
        return link;
    }

Above I have used a recursive method. It shows that as the passed variable (head or some node's next field) cannot be changed in java, one has to return it assigning it to the same variable.

The code above is not very nicely formulated; write your own logic.

  • Related