为什么此代码显示由于 hackerrank 超时而终止

Why this code is showing terminated due to timeout on hackerrank

问题是 - 合并两个排序的链表。 有关详细信息,请访问 https://www.hackerrank.com/challenges/merge-two-sorted-linked-lists 当我在网站上提交这个时,它显示 "Terminated due to timeout"。请告诉我代码有什么问题,以及如何解决它。

Node MergeLists(Node headA, Node headB) {
 // This is a "method-only" submission. 
 // You only need to complete this method 
if(headA==null){
    return headB;
}else if(headB==null){
    return headA;
}else{
    Node h,t;
    if(headA.data>=headB.data){
        h=headB;
        t=h;
        h=h.next;
        headB=headB.next;
    }else{
        h=headA;
        t=h;
        h=h.next;
        headA=headA.next;
    }
    while(headA!=null && headB!=null){
        if(headA.data>=headB.data){
        h.next=headB;
        h=h.next;
        headB=headB.next;
    }else{
        h=headA;
        h=h.next;
        headA=headA.next;
    }
    }
    if(headB==null){
        h=headA;
    }
    return t;
}

}

代码似乎没有正确合并两个列表,laune 评论了大部分错误,加上 while() 循环中 else 后面的代码需要修复(它应该遵循与如果在 while() 循环中)。发生超时可能不是因为您的代码花费的时间太长,而是因为对返回的合并列表的 hackerrank post 合并检查陷入循环或遵循错误的引用。

尝试创建一个调用 MergeLists 函数的测试程序以对其进行调试。

为了解决 Java 没有指向指针的指针的限制,您可以使用虚拟节点简化代码:

    Node t = new Node;
    Node h = t;
    // ... h.next = ... merge the lists while advancing h
    return t.next;