尝试在我正在创建的自定义链接列表中实现这三种方法时遇到了很多麻烦。即使我有一个现有的链接列表,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));
在 sysout 处返回 NullPointer 异常