I am trying to create my own LinkedList in Java and so far it is working as expected. It can take inputs and print them. But, there is a remove method that takes the index as the argument that the user wants to remove from the LinkedList which is throwing an error. Please help me get rid of that error or otherwise suggest how to implement the remove method to make it work correctly.
MyLinkedList.java
import Node.*;
public class MyLinkedList {
Node head;
int val;
public MyLinkedList(int val){
this.head = new Node(val, null);
}
public void insert(int val){
if (this.head == null){
this.head = new Node(val, null);
}
else{
Node node = this.head;
while (node.next!=null){
node = node.next;
}
node.next = new Node(val, null);
}
}
public void remove(int index){
int count = 0;
// int size = 0;
Node node = this.head;
while(node!=null){
node = node.next;
count++;
}
if (index == count){
node = this.head;
count = 0;
while (count<index){
node = node.next;
count++;
}
node.next = null;
return;
}
while(count<index){
node = node.next;
count++;
}
Node temp;
temp = node.next;
node = temp;
}
public void print(){
Node node = this.head;
while (node != null){
System.out.println(node.val);
node = node.next;
}
}
public static void main(String[] args) {
MyLinkedList ll = new MyLinkedList(10);
ll.insert(20);
ll.insert(30);
ll.insert(40);
ll.insert(50);
ll.print();
ll.remove(3); //error
ll.print();
}
}
Node.java is defined inside a folder named "Node" (package)
package Node;
public class Node {
public int val;
public Node next = null;
public Node(int val, Node next){
this.val = val;
this.next = next;
}
}
Output:
10
20
30
40
50
Exception in thread "main" java.lang.NullPointerException: Cannot read field "next" because "<local3>" is null
at MyLinkedList.remove(MyLinkedList.java:50)
at MyLinkedList.main(MyLinkedList.java:69)
Thank you for any help : )