这里是我写的代码,它工作正常,直到我到达循环,它崩溃显示NullPointerException异常我想将2排序LinkedList合并到一个排序列表,但得到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");
}
}
你会在哪一行得到'NullPointerException'? –
@rD。更新了显示错误区域的答案,我做错了什么? –
我不认为这是完全重复的。 –