我必须为链表类编写一个非常简单的方法,但我遇到了一些问题.这个名为squish()的方法接受此列表,并且无论两个或多个连续项是什么
等于(使用equals()进行比较),它会删除重复的节点,以便只保留一个连续的副本.因此,在完成程序后,该列表中没有两个连续项目是相同的.
在执行squish()之后,列表可能比squish()开始时更短.没有添加额外的项目来弥补被删除的项目.
例如,如果输入列表为[0 0 0 0 1 1 0 0 0 3 3 3 1 1 0],则输出列表为[0 1 0 3 1 0].
这是我的方法:
public void squish() {
SListNode current = head;
boolean end =false;
while(end == false )
{
if(!current.item.equals(current.next.item))
current=current.next;
else
{
while(current.item.equals(current.next.item) && current.next !=null)
current.next=current.next.next;
current=current.next;
}
if (current==null)
end=true;
}
}
这是执行代码的一个小主要部分.
public class main {
public static void main(String args[])
{
int[] test6 = {6, 6, 6, 6, 6, 3, 6, 3, 6, 3, 3, 3, 3, 3, 3};
SList list6 = new SList();
for (int i = 0; i < test6.length; i++) {
list6.insertEnd(new Integer(test6[i]));
}
System.out.println("squishing " + list6.toString() + ":");
list6.squish();
String result = list6.toString();
System.out.println(result);
int[] test5 = {3, 7, 7, 7, 4, 5, 5, 2, 0, 8, 8, 8, 8, 5};
SList list5 = new SList();
for (int i = 0; i < test5.length; i++) {
list5.insertEnd(new Integer(test5[i]));
}
System.out.println("squishing " + list5.toString() + ":");
list5.squish();
result = list5.toString();
System.out.println(result);
}
}
调试代码我可以看到该方法工作正常..只是在列表的末尾他转发了一个空异常指针.你能帮助我吗?谢谢