我试图将2个已排序的LinkedList合并到一个已排序的List中,但是获取NullPointerException?

时间:2016-08-22 03:16:15

标签: java data-structures linked-list mergesort

这是我编写的代码,它工作正常,直到我进入循环,它崩溃显示 NullPointerException

看起来我在这里遗漏了一些非常基本的东西..但是当我在笔和笔上运行算法时我根本没有看到任何问题。

我做错了什么,请帮忙!

package lesson.datastructure;

public class MergeSort {

    public static Node getSortedNode1(){
        Node n1=new Node();
        n1.value=2;
        Node n2=new Node();
        n2.value=76;
        Node n3=new Node();
        n3.value=98;
        n1.next=n2;
        n2.next=n3;
        n3.next=null;
        return n1;
    }
    public static Node getSortedNode2(){
        Node n1=new Node();
        n1.value=23;
        Node n2=new Node();
        n2.value=65;
        Node n3=new Node();
        n3.value=87;
        n1.next=n2;
        n2.next=n3;
        n3.next=null;
        return n1;
    }
    public static void printNode(Node head,String name){

        System.out.println(name);
        while(head!=null){
            System.out.print(head.value+"->");
            head=head.next;
        }
        System.out.println("\n\n");
    }

    /* Main method ignore all other methods */
    public static void main(String[] args){

        Node head1,head2;
        head1=getSortedNode1();
        head2=getSortedNode2();

        printNode(head1, "List 1");
        printNode(head2, "List 2");

        Node sortedMergedList=null;

        if(head1.value<head2.value){
            Node nextNode=head1.next;
            Node isolatedNode=null;
            isolatedNode=head1;
            isolatedNode.next=sortedMergedList;
            sortedMergedList=isolatedNode;
            head1=nextNode;
        }
        else
        {
            Node nextNode=head2.next;
            Node isolatedNode=null;
            isolatedNode=head2;
            isolatedNode.next=sortedMergedList;
            sortedMergedList=isolatedNode;
            head2=nextNode;
        }


        while(head1!=null || head2!=null){
       //Null pointer here while accessing head1 or head2
            if(head1.value<head2.value){
                Node nextNode=head1.next;
                Node isolatedNode=null;
                isolatedNode=head1;
                isolatedNode.next=sortedMergedList;
                sortedMergedList=isolatedNode;
                head1=nextNode;
            }
            else
            {
                Node nextNode=head2.next;
                Node isolatedNode=null;
                isolatedNode=head2;
                isolatedNode.next=sortedMergedList;
                sortedMergedList=isolatedNode;
                head2=nextNode;
            }

        }
            printNode(sortedMergedList, "merged sorted list");

    }


    }

1 个答案:

答案 0 :(得分:0)

我认为选择head的条件应该是value和isNull,所以isNull条件应该添加如下。

if(head1!=null&&(head2==null||head1.value<head2.value)){