This code below is an implementation of linked List data structure.
I'm using Bubble sorting to sort its elements.
When I'm entering more than 4
elements, it throws a NullPointerException
.
My code:
public class Main {
Node head = null;
Scanner sc = new Scanner(System.in);
int number;
void insert() {
System.out.println("Enter the number of data. ");
number = sc.nextInt();
for (int i = 0; i < number; i++) {
System.out.println("Enter the data.");
int data = sc.nextInt();
Node n = new Node(data);
if (head == null) {
head = n;
} else {
n.next = head;
head = n;
}
}
}
void sorting() {
Node temp = head;
for (int i = 0; i < number - 2; i++) {
for (int k = 0; k < number - i - 2; k++) {
while (temp.data > temp.next.data) {
int data1 = temp.data;
temp.data = temp.next.data;
temp.next.data = data1;
System.out.println(2);
}
System.out.println(1);
temp = temp.next;
}
}
}
void print() {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
}
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
public static void main(String[] args) {
Main n = new Main();
n.insert();
n.sorting();
n.print();
}
}
How can I fix this?