在我的单链表实现中运行NullPointerException

时间:2015-04-27 09:30:17

标签: java nullpointerexception singly-linked-list

所以我正在研究单链表的实现,我遇到了可怕的空指针异常。这是我的代码:

class Link
{
   public Object data;
   public Link next;
}

class List
{
   private Link _head;
   private Link _tail;
   private int counter = 0;

   public List()
   {
      _head = null;
      _tail = null;
   }

   public void insert(Object item, int pos)
   {
      if (pos == counter)
      {
         insertAtEnd(item);
         return;
      }

      Link temp = _head;
      for (int i = 1; i < pos; ++i)
      {
         temp = temp.next;
      }

      Link added = new Link();
      added.data = item;
      added.next = temp.next;
      temp.next = added;
      ++counter;
   }

   public void insertAtEnd(Object item)
   {
      if (_head == null)
      {
         Link added = new Link();
         added.data = item;
         added.next = _tail;
         _head = added;
      }
      else
      {
         _tail.next = new Link();
         _tail = _tail.next;
         _tail.data = item;
      }
      ++counter;

   }

   public void deleteRange(int start, int end)
   {
      Link temp = _head;
      Object deleted;

      for (int i = 1; i < start - 1; ++i)
      {
         temp = temp.next;
      }
      for (int i = start; i < end; ++i)
      {
         deleted = temp.next.data;
         temp = temp.next;
         --counter;
      }
      temp.next = temp.next.next;
   }

   public void deleteAll(Object item)
   {
      Link temp = _head;
      Link temp2 = _head;
      Link prev = null;
      Object deleted;
      int times = 0;

      for (int i = 1; i <= counter; ++i)
      {
         if (temp.data.equals(item))
            ++times;
         temp = temp.next;      
      }

      for (int i = 1; i <= counter; ++i)
      {
         prev = temp2;
         if (temp2.data.equals(item))
         {
            deleted = temp2.data;
            temp2 = prev;
         }
         temp2 = temp2.next;

      }
      counter = counter - times;
   }

   public Object retrieve(int pos)
   {
      Link temp = _head;

      for (int i = 1; i < pos; ++i)
      {
         temp = temp.next;
      }
      return temp.data;
   }

   public List find(Object item)
   {
      Link temp = _head;
      Link prev = null;
      int count = 0;
      boolean found = false;
      List positions = new List();
      positions.insertAtEnd((Integer) count);
      return positions;

   }

   public int getSize()
   {
      return counter;
   }

   public String toString()
   {
      Link temp = _head;
      String s = "";
      while (temp.next != null)
      {
         s += temp.data + ", ";
         temp = temp.next;
      }   
      return s;   
   }

当调用toString方法测试我的代码时,会弹出空指针异常。我认为我的问题在于我的插入方法,但我不完全确定。我对编程很新,我不能完全围绕单链表动态数据结构

提前致谢!

1 个答案:

答案 0 :(得分:0)

我认为,在你的函数InsertAtEnd()中,你没有在第一个if条件下初始化_head。