Я изучаю структуры данных.Поэтому я пытаюсь реализовать doubly linked list in Java.
Я пытаюсь реализовать insertAtAnyPosition
метод
Используя этот метод, я могу вставить значение по любому указанному индексу.
public class DoublyLinkedList {
Node head = null;
public void insert(int data) {
Node node = new Node();
node.data = data;
node.next = null;
if(head == null)
head = node;
else {
Node n = head;
while(n.next != null ) {
n = n.next;
}
n.next = node;
node.previous = n.next;
}
}
public void insertAtStart(int data) {
Node node = new Node();
node.previous = null;
node.data = data;
head.previous = node;
node.next = head;
head = node;
}
public void insertAtAnyPosition(int index, int data) {
Node node = new Node();
node.data = data;
Node n = head;
for (int i = 0; i < index-1; i++) {
n = n.next;
}
Node n1 = n.next.previous;
node.previous = n1;
node.next = n.next;
n.next = node;
n1 = node;
}
public void display() {
Node n = head;
while(n.next != null) {
System.out.println(n.data);
n = n.next;
}
System.out.println(n.data);
}
}
Класс узла
public class Node {
int data;
Node next;
Node previous;
}
Основной метод
public static void main(String[] args) {
// TODO Auto-generated method stub
DoublyLinkedList list = new DoublyLinkedList();
list.insert(12);
list.insert(4);
list.insert(1);
list.insert(30);
list.insertAtAnyPosition(4,100); // Null Pointer Exception thrown when trying to insert at 4th Index.
list.display();
}
"Null Pointer Exception"
выбрасывается при попытке вставить элемент в 4th Index
.И в этой строке выдается исключение Node n1 = n.next.previous;
Но приведенный выше код работает, когда я пытаюсь вставить элемент с индексом 1,2,3
, но не в 4. Может ли кто-нибудь помочь мне, как решить эту проблему?