I am a beginner in java and have just started working with linked lists. I have written a simple program in java that creates a linked list having only one node with head and tail pointing to the same single node. However, I had some doubts that needed to be clarified and would be grateful to anyone who can clear them.
Here is the code:
- Node.java class
public class Node{
public int value;//Declared value field for node
public Node next;//Declared link to next node in java
}
- SinglyLinkedList.java class
public class SinglyLinkedList{
public Node head;//DEclared head node
public Node tail;//Declared tail node
public Node createsSinglyLinkedList(int inputvalue){
head=new Node();//Memory allocation using new operator
tail=new Node();//Memory allocation using new operator
Node node=new Node();//Creation of node object and allocation of memory using new operator
node.next=null;//Since there is single node it point to null as there are no nodes after it
node.value=inputvalue;//input value field
head=node;//Memory address of node allocated to next of head as it id first element.
tail=node;//Memory address of node allocated to next of tail as it is also last element.
return head;
}
}
- Main.java class
class Main {
public static void main(String[] args) {
SinglyLinkedList sLL=new SinglyLinkedList();//sLL object creation and memory allocation
sLL.createsSinglyLinkedList(5);//Value inserted
System.out.println(sLL.head.value);//Linked list printed
}
}
Here are my questions:
1.System.out.println(sLL.head.value); gives correct output 5. However, System.out.println(sLL.node.value) shows Symbol not found? Is is because Node node=new Node(); creates node object that is local variable while head is instance variable that can be accessed by sLL object .
2.If it is really a local variable will the node object be stored on heap memory or stack memory as read somewhere that local variables are stored on stack memory.
3.Will start be stored in stack or heap memory?
4.Are these Statements correct:
head=node;//Memory address of node allocated to next of head as it id first element.
tail=node;//Memory address of node allocated to next of tail as it is also last element.
5.Also,what does (sLL.head.value) actually do?