1

在我可以访问我的代码之前,我得到了一个空指针异常。我无法判断它是否会正常工作,因为我无法让它通过这一点。

此行中抛出错误:

if(currentNode.getData() > currentNode.getNext().getData())

这是我的冒泡排序:

public static void bubbleSort(DoubleLinkedList list) //static method used to sort the linked list using bubble sort
      {
          int i = 0;
          int j = 0;
          Node currentNode = list.head;
          Node previousNode = currentNode;
          Node tempNext =  currentNode;
          Node tempPrevious = currentNode;


          for(i=1; i<list.getSize(); i++)
          {
              for(j=0; j<list.getSize()-1; j++)
              {
                  if(currentNode.getData() > currentNode.getNext().getData())
                  {
                      if(currentNode == list.head)
                      {
                          Node tempNode = currentNode.getNext();

                          list.head = tempNode;
                          tempNext = tempNode.getNext();

                          tempNode.setNext(currentNode);
                          currentNode.setNext(tempNext);
                          currentNode.setPrevious(tempNode);

                          tempNext.setPrevious(currentNode);
                      }
                      else if(currentNode.getNext() == list.last)
                      {
                          Node tempNode = currentNode.getNext();
                          list.last = currentNode;
                          tempPrevious = currentNode.getPrevious();

                          tempNode.setNext(currentNode);
                          tempNode.setPrevious(tempPrevious);

                          currentNode.setPrevious(tempNode);
                      }
                      else
                      {
                          Node tempNode = currentNode.getNext();
                          tempPrevious = currentNode.getPrevious();
                          tempNext = currentNode.getNext();

                          tempPrevious.setNext(tempNode);
                          tempNext.setPrevious(currentNode);

                          currentNode.setNext(tempNext);
                          tempNode.setPrevious(tempPrevious);
                      }

                  }

                  currentNode = currentNode.getNext();

              }
          }



      }

我认为对循环的限制将使编译器无法尝试访问不一定存在的指针,这就是我理解的空指针异常。

如果有人可以帮助我克服这个错误,以便我可以测试我的冒泡排序,我将非常感激!

4

2 回答 2

1

要么currentNode为空,要么currentNode.getNext()返回空,这就是你不能调用getData()它的原因。在使用节点之前,您应该始终检查节点是否存在空值。

于 2012-09-26T03:12:01.180 回答
1

If currentNode and currentNode.getNext() being or returning null don't cause the problem, then I'd guess that the getData() methods do not return a primitive data type (like int) but an object (like Integer).

In this case getData() could return null and the out-boxing, the automatic conversion of a wrapper class instance to its wrapped primitive type, that is needed for the < operation, would fail and cause a NPE.

于 2012-09-26T04:33:05.643 回答