For the meantime, I'm trying to figure out the basics of how Circular Singly Linked List works. In this case, I'm creating a program in which, user can input from 1 to 3, the number of linked nodes. However, I'm stuck for over 5 hours and can't find a solution elsewhere on this problem. It says that I cannot assign data on my Node because it is null, but I already assigned it to a newnode.
After figuring this 1-3 node circular singly linked list. I'm planning on increasing the nodes.
The IDE says this:
Exception in thread "main" java.lang.NullPointerException: Cannot assign field "data" because "DS2.prac2.head" is null
at DS2.prac2.inc(prac2.java:47)
at DS2.prac2.Start(prac2.java:34)
at DS2.prac2.main(prac2.java:104)
My code:
package DS2;
import java.util.Scanner;
public class prac2{
static class Node {
int data;
Node next;
}
static Node head;
static Node tail;
static Node current;
public static int num;
public prac2(){
num=0;
}
static void Start(int n){ //Starts the program
for(int i=0; i<n;i++){ //A loop to create nodes
inc();
}
}
static void inc(){ //the method for each nodes created
Node newnode = new Node();
newnode.data=num;num++;
newnode.next=head;
if(num==1){
newnode=null;
head.data=num;num++;
head.next=head;
}
else if(num==2){
tail=newnode;
head.next=tail;
}
else{
tail.next=newnode;
tail=newnode;
}
}
static void Display(){ //For Displaying the Circular List
int temp1=0;
current=head;
do{
if(current==head) //If current passed head twice it means that it passed through all the nodes
temp1++;
System.out.println(current.data);
current=current.next;
}
while(temp1==1);
}
public static void main(String[] args) {
int M,N;
Scanner scan = new Scanner(System.in);
// M=scan.nextInt();
System.out.print("Input how many nodes (1-3): ");
N=scan.nextInt();
Start(N);
scan.close();
}
}```