[英]Merging two sorted linkedlists
我正在嘗試編寫一個程序來合並兩個排序的鏈表。但最后一個元素根本沒有插入。 嘗試在 listA 中的最后一個節點之后插入一個節點時,代碼似乎失敗了。 任何幫助,將不勝感激。
/*
Merge two sorted lists A and B as one linked list
Node is defined as
struct Node
{
int data;
struct Node *next;
}
*/
Node* MergeLists(Node *headA, Node* headB)
{
// This is a "method-only" submission.
// You only need to complete this method
Node *prev;
Node *currentA=headA;
Node *currentB=headB;
Node *next;
if(headA==NULL)
{
return headB;
}
if(headB==NULL)
{
return headA;
}
while(currentA!=NULL && currentB!=NULL)
{
if(currentB->data < currentA->data)
{
Node *new_node=new Node;
new_node->data=currentB->data;
headA=new_node;
new_node->next=currentA;
currentA=new_node;
currentB=currentB->next;
}
else if(currentB->data > currentA->data && currentB->data < currentA->next->data)
{
Node *new_node=new Node;
new_node->data=currentB->data;
next=currentA->next;
prev=currentA;
new_node->next=next;
prev->next=new_node;
currentA=new_node;
currentB=currentB->next;
}
else
{
currentA=currentA->next;
}
if(currentA->next==NULL)
{
Node *new_node=new Node;
new_node->data=currentB->data;
prev=currentA;
prev->next=new_node;
new_node->next=NULL;
currentA=new_node;
currentB=currentB->next;
}
}
return headA;
}
輸入:
1 (No of test cases)
2 (Length of list A)
2 4
4 (Length of list B)
1 3 5 7
預期輸出:
1 2 3 4 5
實際輸出:
Runtime error
我認為真正的問題在於您的意見。
1(測試用例數)
2(列表A的長度)
2 4
2(列表B的長度)
1 3 5
列表 B 的長度應為 3。正如您在輸入中提到的 2。 您的輸出僅包含列表 B 中的 2 個元素。
請檢查正確的輸入如下:
1(測試用例數)
2(列表A的長度)
2 4
3(列表B的長度)
1 3 5
當代碼到達列表 A 或列表 B 的末尾時,它缺少復制列表 A 或列表 B 的其余部分的代碼。我還想知道在設置 currentA = currentA->next 后使用 currentA->next 進行檢查,這可能是NULL。
代碼也很復雜,如果(currentB->data < currentA->data),你從列表B中移動或復制一個節點,否則你從列表A中移動或復制一個節點,則不需要復雜的else if after (currentB->data < currentA->data),只要 else 就足夠了。
代碼可以簡化:
prev = NULL; /* this will be sorted list */
/* ... */
if(prev == NULL){ /* if first element */
prev = new_node;
next = new_node;
} else {
next->next = new_node;
next = new_node;
}
/* ... */
next->next = NULL; /* set end of list */
您可能需要考慮將 prev 的名稱更改為 head 和 next to tail。
通常,mergelists 函數將節點從列表 A 和列表 B 移動到排序的輸出列表中,而不是創建節點的副本列表。 在這種情況下,將永遠不會使用新節點,並且列表 A 和列表 B 中的現有節點將按順序鏈接在一起。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.