我昨天发布了一个问题,我正在重写此程序的toString(),但现在我遇到了另一个问题。 removeItem()方法应该删除具有给定数据值的节点(在本例中为String名称)。我在第64行得到了一个NullPointerException,我似乎无论如何都无法理解它。我的代码在下面,并提前感谢任何帮助。从单个链表中删除特定节点
public class StudentRegistration<E>
{
private static class Node<E>
{
/** The data value. */
private E data;
/** The link */
private Node<E> next = null;
/**
* Construct a node with the given data value and link
* @param data - The data value
* @param next - The link
*/
public Node(E data, Node<E> next)
{
this.data = data;
this.next = next;
}
/**
* Construct a node with the given data value
* @param data - The data value
*/
public Node(E data)
{
this(data, null);
}
public Node getNext()
{
return next;
}
public E getData()
{
return data;
}
public void setNext(Node append)
{
next = append;
}
}
/** A reference to the head of the list */
private Node<E> head = null;
/** The size of the list */
private int size = 0;
/** Helper methods */
/** Remove the first occurance of element item.
@param item the item to be removed
@return true if item is found and removed; otherwise, return false.
*/
public void removeItem(E item)
{
Node<E> position = head;
Node<E> nextPosition1,
nextPosition2;
while (position != null)
{
if(position.getNext().getData() == item) //NullPointerException
{
nextPosition1 = position.getNext();
nextPosition2 = nextPosition1.getNext();
position.setNext(nextPosition2);
}
else
{
position = position.getNext();
}
}
}
/** Insert an item as the first item of the list.
* @param item The item to be inserted
*/
public void addFirst(E item)
{
head = new Node<E>(item, head);
size++;
}
/**
* Remove the first node from the list
* @returns The removed node's data or null if the list is empty
*/
public E removeFirst()
{
Node<E> temp = head;
if (head != null)
{
head = head.next;
}
if (temp != null)
{
size--;
return temp.data;
} else
{
return null;
}
}
/** Add a node to the end of the list
*@param value The data for the new node
*/
public void addLast(E value)
{
// location for new value
Node<E> temp = new Node<E>(value,null);
if (head != null)
{
// pointer to possible tail
Node<E> finger = head;
while (finger.next != null)
{
finger = finger.next;
}
finger.setNext(temp);
} else head = temp;
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("[");
Node<E> aux = this.head;
boolean isFirst = true;
while(aux != null)
{
if(!isFirst)
{
sb.append(", ");
}
isFirst = false;
sb.append(aux.data.toString());
aux=aux.next;
}
return sb.append("]").toString();
}
}
换句话说小心回避:告诉我们哪一行“第64行”是。对该行发表评论,或者给我们一些其他提示。是的,我们可以将它复制到一个编辑器中并做出一个很好的猜测,但我们不应该这样做才能获得这种基本信息。 – keshlam
我的错误,我添加了一条评论 –
你应该检查'position.next'是否为'null'而不是'position'。 –