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;
}
}