Java LinkedList实现插入方法第0个索引插入处理
我已经实现了链表的以下java实现Java LinkedList实现插入方法第0个索引插入处理,java,algorithm,data-structures,linked-list,Java,Algorithm,Data Structures,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
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;
}
}
}
公共类LinkedListFromScratch{
专用节点头;
私有静态整数大小;
公共LinkedListFromScratch(){
this.head=null;
此值为0.size=0;
}
公共布尔值为空(){
返回头==null;
}
公共静态int getSize(){return size;}
void addToTail(整数数据){
Node newNode=新节点(数据);
//如果列表为空,则将新节点设为头部。
if(isEmpty()){
this.head=newNode;
大小++;
返回;
}
节点头=头部;
while(iterthead.next!=null){
itterHead=itterHead.next;
}
itterHead.next=newNode;
大小++;
}
void addAtIndex(整数索引,整数数据){
如果(索引<0 | |索引>this.size)
抛出新的IllegalArgumentException(“您输入的索引超出范围”);
Node newNode=新节点(数据);
if(isEmpty()){
this.head=newNode;
大小++;
返回;
}
//将obj定位在索引处,并在其前面找到一个
//newnode.next=obj
//prevnode.next=newnode
节点电流=this.head;
Node-previous=null;
对于(int i=0;i
这里的问题是addAtIndex(int-index,int-data)方法。当我尝试在索引0处插入一个值时,它抛出一个空指针异常。这是有意义的,因为for循环永远不会执行,并且在index=0场景中,“previous”将始终为null。对于索引>0,插入工作正常。处理这种情况的最佳方法是什么?您需要检查索引是否为零,这意味着您有了新的列表标题 在for循环之前添加此代码
if (index == 0){
newNode.next = head;
head = newNode;
size++;
return;
}
你应该把它作为一个单独的案例来处理。