我昨天發佈了一個問題,我正在重寫此程序的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'。 –