1

I am working on trying to split my doubly linked list. But i get nullpointer exception on sublist.head = mid.next. Does it means sublist.head is pointing to null? How can i resolve this??

public void splitMid(DoublyLinkedList<T> sublist)
{
    Node<T> current;
    Node<T> mid;
    int i;
    if (head == null)
    {
        sublist.head = null;
        sublist.rear = null;
        sublist.count = 0;
    }
    else
        if (head.next == null)
        {
            sublist.head = null;
            sublist.rear = null;
            sublist.count = 0;
        }
        else
        {
            mid = head;
            current = head.next;
            i = 1;
            if (current != null)
                current = current.next;
            while (current != null)
            {
                mid = mid.next;
                current = current.next;
                i++;
                if (current != null)
                    current = current.next;
            }
            sublist.head = mid.next;
            sublist.rear = rear;
            rear = mid;
            rear.next = null;
            sublist.count = count - i;
            count = i;
        }

}
J. Koh
  • 75
  • 1
  • 8
  • Unless you are working on this in order to learn how to implement a double linked list, I would suggest you use `LinkedList` instead, which is a double linked list... – Per Huss Jun 13 '16 at 07:32

1 Answers1

2

If this statement:

 sublist.head = mid.next;

(taken in isolation) is throwing an NPE, it means that:

  • sublist is null, OR
  • mid is null, OR
  • both of them are null.

(You could figure out which with either a debugger & conditional breakpoints, or by adding some temporary trace prints or assertions.)

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • I thought (a || b) covers the (a && b) case already... Why so explicit? :) – buræquete Jun 13 '16 at 07:36
  • 1
    'cos I'm a pedant ... and OR is not a Java operator :-) – Stephen C Jun 13 '16 at 07:37
  • Am i right to think that previous is not needed here as it is splitting hence it is just next – J. Koh Jun 13 '16 at 07:37
  • 1) I don't understand what you are saying. 2) I haven't analysed your code. I am simply telling you that there are TWO possible reasons why that statement could throw an NPE. (Figuring out what the real problem is, and correcting it is .... your homework, not mine.) – Stephen C Jun 13 '16 at 07:40