[英]Java LinkedList implementation insert method 0th index insertion handling
I have implemented the following java implementation of a linked list我已经实现了如下 java 实现了一个链表
public class LinkedListFromScratch {
private Node head;
private static int size;
public LinkedListFromScratch() {
this.head = null;
this.size = 0;
}
public boolean isEmpty() {
return head == null;
}
public static int getSize() {return size;}
void addToTail(int data) {
Node newNode = new Node(data);
//if list is empty, make new node the head.
if (isEmpty()) {
this.head = newNode;
size++;
return;
}
Node itterHead = head;
while (itterHead.next != null) {
itterHead = itterHead.next;
}
itterHead.next = newNode;
size++;
}
void addAtIndex(int index, int data) {
if(index < 0 || index > this.size )
throw new IllegalArgumentException("Index you entered is out of bounds");
Node newNode = new Node (data);
if(isEmpty()) {
this.head = newNode;
size++;
return;
}
//locate the obj at index and one before it
//newnode.next = obj
//prevnode.next = newnode
Node current = this.head;
Node previous = null;
for ( int i = 0; i < index; i++){
previous = current;
current = current.next;
}
previous.next = newNode;
newNode.next = current;
size++;
}
void printList() {
if (isEmpty())
System.out.print("[]");
Node itterHead = this.head;
System.out.print("[ ");
while (itterHead != null) {
System.out.print(itterHead.d + " ");
itterHead = itterHead.next;
}
System.out.print("]");
System.out.println();
}
class Node {
int d;
Node next;
Node(int d) {
this.d = d;
this.next = null;
}
}
}
The issue here is with the addAtIndex (int index, int data) method.这里的问题在于 addAtIndex (int index, int data) 方法。 When I try to insert a value at index zero, it throws a null pointer exception.当我尝试在索引零处插入一个值时,它会引发 null 指针异常。 It makes sense because the for loop never gets executed and "previous" will always be null in the index = 0 scenario.这是有道理的,因为 for 循环永远不会被执行,并且在 index = 0 场景中,“previous”将始终是 null。 The insertion works fine for index > 0. what is the best way to handle this case?对于索引> 0,插入工作正常。处理这种情况的最佳方法是什么?
you need to check if the index is zero, this means you have new head to the list你需要检查索引是否为零,这意味着你有新的头到列表
add this code before the for-loop在 for 循环之前添加此代码
if (index == 0){
newNode.next = head;
head = newNode;
size++;
return;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.