我在嘗試在我創建的自定義鏈接列表中實現這三個方法時遇到了很多麻煩。即使我有一個現有的鏈接列表,get(int pos)方法對於除第0個索引之外的所有內容都將返回null!我的removeAt(int pos)和insert(int pos,int n)方法具有相同的麻煩。我會包括我認爲相關的一切。在自定義鏈接列表中獲取方法,插入和刪除方法
我的節點類
public class MyNode
{
public int cargo;
public MyNode next;
public MyNode()
{
cargo = 0;
next = null;
}
public MyNode(int i)
{
cargo = i;
next = null;
}
}
我的自定義鏈接列表
public class MyLinkedList
{
MyNode head;
int size;
public MyLinkedList()
{
head = null;
size = 0;
}
public int get(int pos)
{
MyNode current = new MyNode();
for(int i = 0; i <= pos && current != null; i++)
{
if(pos == 0){
current = head;
}else{
current = current.next;
break;
}
}
return current.cargo;
}
public void insert(int pos, int n)
{
MyNode current = new MyNode(n);
MyNode before = new MyNode(get(pos-1));
if(before.next != null)
{
before.next = current.next;
}
else
{
before.next = current;
}
size++;
System.out.println("Inserted " + n + " at position " + pos);
}
public void removeAt(int pos)
{
MyNode before = new MyNode(get(pos -1));
MyNode remove = new MyNode(get(pos));
MyNode after = null;
int cargo = remove.cargo;
if(remove.next != null)
{
after = remove.next;
}
before.next = after;
size--;
System.out.println("Removed " + cargo + " from position " + pos);
}
}
我的測試數據
l.add(17);
l.add(14);
l.add(43);
l.add(50);
System.out.println(l.get(1));
回報s是系統空值的空指針異常