我以前需要幫助調試我的deleteNode方法。它現在可以工作(下面更新版本),但我希望它能夠提供必須刪除頭節點的情況。目前,它返回NullPointerException,我在deleteNode中插入了*。我不知道當時我的任何變量都可以爲null,看到我的while循環要求position
和head
首先不爲null。如何刪除鏈接列表中的特定節點
public class LinkedList
{
private class Node
{
int item;
Node link;
@SuppressWarnings("unused")
public Node()
{
item = Integer.MIN_VALUE;
link = null;
}
public Node(int x, Node p)
{
item = x;
link = p;
}
}
private Node head;
public LinkedList()
{
head = null;
}
public boolean deleteNode (int target)
{
Node position = head;
boolean isGone = false;
while(position != null && head != null)
{
if(position.link == head && position.link.item == target)
{
head = head.link;
isGone = true;
return isGone;
}
*** else if(position.link.item == target && position.link != head)
{
position.link = position.link.link;
isGone = true;
return isGone;
}
position = position.link;
}
return isGone;
}
public void printList()
{
System.out.println("Your list is: ");
Node position = head;
while(position != null)
{
System.out.println(position.item + " ");
position = position.link;
}
System.out.println();
}
}
使用調試器,並找出它沒有正確做什麼 –