user1637192
user1637192

Reputation: 1

Object value null

I'm new to Java and I'm trying to implement a Linked list (I do know a list class exists for this purpose, but doing it from scratch lets me understand how the language works internally)

In the main method, I declare 4 nodes and initialize 3. Head node for the linked list is set to null. The first time the add function is called with parameters head and newNode, head is null, so I initialize head and assign value of newNode to it. In the main method, I expect that head object should have new values set from add method. But head is still null.

I'd appreciate understanding why this is happening.

Apologies if the code is not clean, Thanks plenty!

public class LinkedList
{
    public void add(Node newNode, Node head)
    {
        if(head == null) 
        {
            head = new Node(); 
            head = newNode;              
        }
        else 
        {
            Node temp = new Node(); 
            temp = head; 

            while(temp.next!=null)
            {
                temp = temp.next; 
            }
            temp.next = newNode; 
        }    
    }

    public void traverse(Node head)
    {
        Node temp = new Node(); 
        temp = head; 

        System.out.println("Linked List:: ");

        while(temp.next!=null);  
        {
           System.out.println(" "  + temp.data); 
            temp = temp.next;
        }
    }

    public static void main(String args[])
    {
        Node head = null;
        Node newNode = new Node(null, 5); 
        Node newNode2 = new Node(null, 15); 
        Node newNode3 = new Node(null,30); 

        LinkedList firstList = new LinkedList(); 

        firstList.add(newNode,head); 

       // Part that I don't understand
       // why is head still null here? 

        if(head==null)
        {
         System.out.println("true");
        }

        firstList.traverse(head); 
        firstList.add(newNode2,head); 
        firstList.traverse(head); 
        firstList.add(newNode3,head); 
        firstList.traverse(head); 

    }

}

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

    public Node(Node next, int data)
    {
        this.next = next; 
        this.data = data; 
    }

    public Node()
    {
        this.next = null; 
        this.data = 0; 
    }

}

Upvotes: 0

Views: 3578

Answers (5)

Eli Turchinsky
Eli Turchinsky

Reputation: 331

Here is better implantation of your Linked List. Please Note:

  1. _head should be a private member
  2. Node is an inner mechanism. you should give a data parameter to your add method instead of a Node object
  3. I Wrote this , simple ,yet base on your code, implementation

    public class LinkedList{
    private Node _head;
    public void add(int data)
    {               
            //Understand this code! What happens if _head=null?                 
            _head=new Node(_head,data); 
            /*
                 //Use the following code for a "Normal" nodes-order
                 if(_head==null)
                    _head=new Node(null,data);
                 else{
                   Node temp=_head;
                   while( temp.next!=null)
                      temp=temp.next;            
                   temp.next=new Node(null,data); 
                 }
            */
    }
    public void traverse()
    {
        System.out.println("Linked List:: ");
        Node temp=_head;
        while(temp!=null){
                System.out.println(" "  + temp.data); 
                temp = temp.next;
        }
    }
    public LinkedList(){
        _head=null;         //null is our lists anchor
    }
    
    public static void main(String args[])
    {
        LinkedList firstList = new LinkedList(); 
    
        firstList.add(5); 
        firstList.traverse(); 
        firstList.add(15); 
        firstList.traverse(); 
        firstList.add(30); 
        firstList.traverse(); 
    
    }
    

    }

Upvotes: 0

songokuhd
songokuhd

Reputation: 175

I think that the problem is inside the "add" function. You are only changing the value of "head" inside the function scope, not outside it. You can find useful information about the way that Java treat passing parameters values here.

A good implementation of LinkedList in Java is here.

Upvotes: 2

obataku
obataku

Reputation: 29646

Java method arguments are pass-by-value.

public void add(Node newNode, Node head)
{
    if(head == null) 
    {
        head = new Node(); 
        head = newNode;              
    }
    ...

The above only modifies the local variable head in the scope of add. A reference to the local variable head in the scope of main is not possible. Perhaps you should return the value if you want the caller to be able to retrieve the new value.


To be completely honest, a major principle of object-oriented programming is to encapsulate; the head of your LinkedList should ideally be a field maintained internally. Why should it be a separate part? If you really wish to have the head isolated, then why aren't traverse and add static? You should try to revise your design. I decided to rewrite your code here.

final class List {

  private Node head;

  public void add(final Node node) {
    if (head == null) {
      head = new Node();
    }
    Node cur;
    for (cur = head; cur.next != null; cur = cur.next)
      ;
    cur.next = node;
  }

  public String toString() {
    final StringBuilder builder = new StringBuilder("Linked List::");
    for (Node cur = head.next; cur != null; cur = cur.next) {
      builder.append("\n ").append(cur.data);
    }
    return builder.toString();
  }
}

final class Node {

  int data;
  Node next;

  Node(final int data) {
    this.data = data;
  }

  Node() { }
}

... then, to test:

  private static Node[] nodesFor(final int... values) {
    int n = values.length;
    final Node[] nodes = new Node[n];
    while (n > 0) {
      nodes[--n] = new Node(values[n]);
    }
    return nodes;
  }

  public static void main(final String[] argv) {
    final List list = new List();
    for (final Node node : nodesFor(5, 15, 30)) {
      list.add(node);
      System.out.println(list);
    }
  }

Upvotes: 2

perilbrain
perilbrain

Reputation: 8197

    firstList.add(newNode,head); 

   /*
    Part you should know is, head is a local variable pointing to null.
    Passing head as parameter doesn't make it feasible to alter this local variable.
    Your check is worthless.
    Make public Node add(Node newNode, Node head) and return head from there.
   */ 
    head=firstList.add(newNode,head);

    if(head==null)
    {
     System.out.println("true");
    }

Upvotes: 0

Bohemian
Bohemian

Reputation: 425013

Making "head" reference another node has no effect on the calling code (java passes references, which in java are the "values" of the addresses).

You need a permanent reference to the head, so make it a field of your class:

private Node head = new Node(); // the head of your Node tree

public void add(Node newNode, Node parent) {
    // add node to parent.
    // for some calls, the parent will be the head
}

Upvotes: 1

Related Questions