我正在尝试合并两个链表。我编写了以下代码,从ListB中挑选节点并将其链接到适当位置的listA。但是我得到空指针异常,无法弄清楚为什么..请帮助
Node sortedMerge(Node headA, Node headB) {
if(headB.data<=headA.data){
Node temp = headB.next;
headB.next=headA;
headA=headB;
if (temp == null) return headA;
else return sortedMerge(headA, temp);
}
else{
Node headAtemp = headA;
while(headA.next.data <headB.data && headA.next!=null){
headA = headA.next;
}
Node next = headA.next;
Node temp = headB.next;
//changing links
headA.next= headB;
headB.next = next;
if (temp == null) return headAtemp;
else return sortedMerge(headAtemp,temp);
}
}
该函数应返回已排序列表的开头。
答案 0 :(得分:1)
更改顺序,以便从左到右读取
while(headA.next!=null && headA.next.data <headB.data ){