2012-11-04 40 views
0

我制作了一个单链表,但我不断收到NullPointerException。插入方法应该添加一个对象到单独链接列表,然后我把SLL的所有元素放到MyVector类中,然后使用我为MyVector类创建的快速排序algorythm,然后将对象放回到SSL中。我不完全确定为什么我一直在收到错误。将对象/整数插入单链表并对其进行排序

在java.lang.Integer.compareTo(Integer.java:37)在线程 “主” 显示java.lang.NullPointerException 在java.lang.Integer.compareTo(Integer.java:978) 异常 在collection.SortedSLList.remove(SortedSLList.java:51) at collection.SortedSLList.insert(SortedSLList.java:39) at lab.Lab6.test(Lab6.java:15) at main.Main.main(Main的.java:15) Java结果:1

public void insert(Object element) { 
    if(head == null) { 
     head = tail = new SLListNode(element, null); 
     ++size; 
     return; 
    } 
    tail = tail.next = new SLListNode(element, null); 
    ++size; 
    MyVector temp = new MyVector(); 
    int i = size; 
    Object t = head.data; 
    while(temp.size() < i) { 
     temp.append(t); 
     remove(t); //this line 
     t = head.next; 
    } 
    MySort.quickSort(temp); 
    i = 0; 
    while(size < temp.size()) { 
     insert(temp.elementAt(0)); 
     ++i; 
    } 
} 
public boolean remove(Object element) { 
    if(head == null) return false; 
    if(((Comparable)(head.data)).compareTo(element) == 0) { //this line 
     if(head == tail) { 
      head = tail = null; 
      return true; 
     } 
     head = head.next; 
     return true; 
    } 
    if(head == tail) return false; 
    SLListNode ref = head; 
    while(ref.next != tail) { 
     if(((Comparable)(ref.next.data)).compareTo(element) == 0) { 
      ref.next = ref.next.next; 
      return true; 
     } 
     ref = ref.next; 
    } 
    if(((Comparable)(tail.data)).compareTo(element) == 0) { 
     tail = ref; 
     tail.next = null; 
     return true; 
    } 
    return false; 
} 
+2

你可以发布你的堆栈跟踪,或者让我们知道错误是什么行 – PermGenError

+0

不知道什么stacktrace是,但我标记了代码中的行,并添加了NetBeans给我的错误消息。 – Schwarz

+0

你发布的异常是stacktrace .. :) – PermGenError

回答

0

问题是,你做的事:

while(temp.size() < i) { 
    temp.append(t); 
    remove(t); //this line 
    t = head.next; 
} 

的问题是,您已删除打印头(T),所以你应该是T设置等于head.data,不head.next

+0

我刚试过这个改变,它产生了相同的结果。 – Schwarz

+0

其实我猜它应该是'head.data',因为你正在删除数据,而不是节点。 – CrazyCasta

1

异常跟踪表示您正在调用remove(null)。出于某种原因,head.data或head.next包含null。我建议你在这里添加打印输出:

Object t = head.data; 
while(temp.size() < i) { 
    System.out.println("Looking at " + t); // <-- add here 
    temp.append(t); 
    remove(t); //this line 
    t = head.next; 
} 

然后看看这些值在做什么。你会看到其中一个出现null。