![](/img/trans.png)
[英]Why i am getting Terminated due to timeout in this code on Hackerrank? My last iteration is not taking place?
[英]Why this code is showing terminated due to timeout on hackerrank
問題是-合並兩個排序的鏈表。 有關詳細信息,請訪問https://www.hackerrank.com/challenges/merge-two-sorted-linked-lists。當我在網站上提交此文件時,它顯示為“由於超時而終止”。請告訴我代碼有什么問題,以及解決方法。
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()中if的相同邏輯。 )循環)。 發生超時的原因可能不是因為您的代碼花費了太長時間,而是因為返回的合並列表上的hackerrank合並后檢查被卡在一個循環中或遵循了錯誤的引用。
嘗試創建一個調用MergeLists函數的測試程序以對其進行調試。
為了避免Java沒有指針的限制,您可以使用虛擬節點簡化代碼:
Node t = new Node;
Node h = t;
// ... h.next = ... merge the lists while advancing h
return t.next;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.