java - 如何删除链表中所有出现的项目?
问题描述
我是链表的初学者,这是我第一次尝试编写一个方法调用 removeall(N),它将删除列表中某个元素的所有出现。我遍历列表,如果我看到一个等于 n 的元素,我会删除链接,但是我收到一条错误消息
Exception in thread "main" 22 at LinkList.removeAll(LinkList.java:34)
java.lang.NullPointerException
有人可以解释一下我做错了什么吗?
链接.java
class Link
{
public long iData; // data item
public Link next; // next link in list
// -------------------------------------------------------------
public Link(long id) // constructor
{
iData = id; // initialize data
// ('next' is automatically
} // set to null)
// -------------------------------------------------------------
public void displayLink() // display ourself
{
System.out.print("{" + iData + "} ");
}
} // end class Link
链表.java
class LinkList
{
private Link first; // ref to first item on list
// -------------------------------------------------------------
public LinkList() // constructor
{
first = null; } // no items on list yet
// -------------------------------------------------------------
public boolean isEmpty() // true if list is empty
{
return (first==null); }
// -------------------------------------------------------------
public void insertFirst(long dd) // insert at start of list
{ // make new link
Link newLink = new Link(dd);
newLink.next = first; // newLink --> old first
first = newLink; // first --> newLink
}
// -------------------------------------------------------------
//public long deleteFirst() // delete first item
public Link deleteFirst() // delete first item
{ // (assumes list not empty)
Link temp = first; // save reference to link
first = first.next; // delete it: first-->old next
return temp; // return deleted link
}
public void removeAll(int n) {
Link current = first; // start at beginning of list
while(current != null) {
current = current.next;
if(current.iData==n) {
current.next=current.next.next;
}
}
}
// -------------------------------------------------------------
public void displayList()
{
System.out.print("List (first-->last): ");
Link current = first; // start at beginning of list
while(current != null) // until end of list,
{
System.out.print("List (first-->last): "+ current.iData); // print data
current = current.next; // move to next link
}
System.out.println("");
}
// -------------------------------------------------------------
} // end class LinkList
解决方案
以下是您的 removeAll 实施中的一些问题:
if(current.iData==n)
检查当前列表项的值,但current.next=current.next.next;
删除下一项。- 您不处理列表开头的匹配项。
尝试以下 removeAll 方法的实现:
public void removeAll(int n) {
// handling elements from the beginning
while(first != null && first.iData == n){
first = first.next;
}
// Removing matched elements from the rest of the list
Link current = first;
while (current != null && current.next != null ) {
if (current.next.iData == n) {
current.next = current.next.next;
} else {
current = current.next;
}
}
}