我被赋予了这个代码来编写多个类,但是我很难理解这个LinkList。当调用我的clear()和我的count(E o)方法(这两个是写入时需要的)时,我不知道如何运行循环。我不确定引用的是我在类中调用的数组的长度,并且不断获取nullpointers。大小是正确的变量还是其他东西?还有点混淆了在main方法中调用count(E o)的人。
public class GenericLinkedList<E> implements List<E> {
private class Node<E>{
private E data;
private Node<E> next;
}
private E data;
private Node<E> head = null;
private int size = 0;
private Node<E> nodeAt(int index){
Node<E> curNode = head;
int curIndex = 0;
while(curIndex < index){
curNode = curNode.next;
curIndex++;
}
return curNode;
}
@Override
public E get(int index) {
return nodeAt(index).data;
}
@Override
public void add(E value) {
Node<E> node = new Node<E>();
node.data = value;
if(size == 0){
head = node;
}else{
Node<E> curNode = nodeAt(size - 1);
curNode.next = node;
}
size++;
}
public void add(int index, E value){
Node<E> node = new Node<E>();
node.data = value;
if(size == 0){
head = node;
}else if(index == 0){
node.next = head;
head = node;
}else{
Node<E> curNode = nodeAt(index - 1);
node.next = curNode.next;
curNode.next = node;
}
size++;
}
@Override
public void remove(int index) {
if(index == 0){
head = head.next;
}else{
Node<E> curNode = nodeAt(index - 1);
curNode.next = curNode.next.next;
}
}
@Override
public void set(int index, E value) {
nodeAt(index).data = value;
}
public String toString(){
String s = "";
Node<E> curNode = head;
s += curNode.data +" -> ";
while(curNode.next != null){
curNode = curNode.next;
s += curNode.data +" -> ";
}
s += "null";
return s;
}
@Override
public void clear()//Clears out the array object by setting everything to null
{
for(int i = 0; i < data.size; i++)
{
remove(0);
}
}
@Override
public int count()
{
int count = 0;
E temp;
for(int i = 0;i<size-1;i++)
{
if(get(i)!=null)
{
count++;
}
else
{
}
}
return count;
}