while studying a linked list implementation i need a clarify how the reference and object store in stack and heap for this kind of scenario where object it self has references,
public class MyLinkedList {
private Node head;
private int listCount;
public MyLinkedList() {
head = new Node("0");
listCount = 0;
}
public void add(Object data) {
Node nodeTemp = new Node(data);
Node nodeCurr = head;
while (nodeCurr.getNext() != null) {
nodeCurr = nodeCurr.getNext();
}
nodeCurr.setNext(nodeTemp);
listCount++;
}
}
public class LinkedListMain {
public static void main(String[] args) {
MyLinkedList ls = new MyLinkedList();
ls.add("1");
}
Now MyLinkedList object is refer by "ls" reference which is in stack and the MyLinkedList it self is in heap. That i understood.
But then from the MyLinkedList constructor when we create new Node which refer by "head" reference where does that "head" reference store? My doubt is since "Node head" is inside (belong to) MyLinkedList object, does "head" store in stack with "ls" or is it kind of inside MyLinkedList object?