有问题的排序双链表(java空指针)

时间:2016-01-27 06:35:34

标签: java data-structures nullpointerexception doubly-linked-list

我正在尝试解决hackerrank的问题。要解决的问题是

“您将获得指向已排序的双向链表的头节点的指针以及要插入列表的整数。创建节点并将其插入列表中的适当位置。头节点可能为NULL表示该列表为空。“

他们提供的Node类定义为

/*
Insert Node at the end of a linked list 
head pointer input could be NULL as well for empty list
Node is defined as 

class Node {
    int data;
    Node next;
    Node prev;
}
*/

我尝试过的解决方案是

Node SortedInsert(Node head,int data) 
{
    // new node to insert into linked list
    Node newNode = new Node();
    newNode.data = data;

    if (head == null)
    {  
        return newNode;
    }

    else
    {
        // start at beginning of list
        Node cur = head;

        // traverse through sorted list
        while (cur != null && cur.next != null)
        {        
            if (data < cur.next.data)
            {
                newNode.next = cur.next;
                newNode.prev = cur;
                cur.next.prev = newNode;
                cur.next = newNode;

                return head;
            }

            else
            {
                cur = cur.next;
            }
        }

        return head;
    }
}

我不太确定这里有什么问题,但hackerrank说我的解决方案不正确。有什么可能出错的想法吗?

1 个答案:

答案 0 :(得分:0)

假设我们的DLL是1 = 2 = 3 = 4 = 5

现在考虑这种情况:向DLL添加6 该循环不包括角落情况。

    while (cur != null && cur.next != null)
    {        
        if (data < cur.next.data)
        {
            newNode.next = cur.next;
            newNode.prev = cur;
            cur.next.prev = newNode;
            cur.next = newNode;

            return head;
        }

        else
        {
            cur = cur.next;
        }
    }

修改:

    if(data < cur.data) {
            newNode.next = cur;
            newNode.prev = null;
            cur.prev = newNode;

            head  = newNode;
            return head;
    }

    while (cur != null)
    {        
        if (data >= cur.data)
        {   
            if(cur.next == null) {
                 newNode.next = cur.next;
                 newNode.prev = cur;
                 cur.next = newNode;

                 return head;    
            }

            newNode.next = cur.next;
            newNode.prev = cur;
            cur.next.prev = newNode;
            cur.next = newNode;

            return head;
        }

        else
        {
            cur = cur.next;
        }
    }