我想合併兩個排序的鏈接列表。這裏我只是想實現我自己的算法。當然,互聯網上有很多解決方案。代碼是:合併兩個排序的鏈接列表
Node* MergeLists(Node *headA, Node* headB)
{
int countA = 0, countB = 0;
while(headA){countA++; headA = headA->next;}
while(headB){countB++; headB = headB->next;}
Node *res, *tres;
res = new Node();
res->next = NULL;
tres = res;
for(int i = 0; i < countA+countB-1; i++)
{
Node* temp = new Node();
temp->next = NULL;
tres->next = temp;
tres = tres->next;
}
while(headA != NULL && headB != NULL)
{
if(headA->data > headB->data)
{
res->data = headB->data;
res = res->next;
headB = headB->next;
}
else if(headA->data < headB->data)
{
res->data = headA->data;
res = res->next;
headA = headA->next;
}
}
while(headA)
{
res = headA;
}
while(headB)
{
res = headB;
}
return res;
}
這只是一個函數,它返回合併鏈表的首地址。
考慮此輸入/輸出例如:
Input (stdin):
3
4
1 3 5 6
3
2 4 7
1
15
1
12
0
2
1 2
My Output (stdout)
0 0 0 0 0 0 0
0 0
0 0
Expected Output
1 2 3 4 5 6 7
12 15
1 2
所以,我的輸出打印所有零。這是由於在這段代碼中的問題:
Node *res, *tres;
res = new Node();
res->next = NULL;
tres = res;
for(int i = 0; i < countA+countB-1; i++)// this is creating a new linked list.
{
Node* temp = new Node();
temp->next = NULL;
tres->next = temp;
tres = tres->next;
}
我認爲tres和res之間的聯繫不正常發生。你能告訴我如何改正這個問題嗎?
更新:
Node* MergeLists(Node *headA, Node* headB)
{
int countA = 0, countB = 0;
Node* tempA, *tempB;
tempA = headA; tempB = headB;
while(headA){countA++; tempA = tempA->next;}
while(headB){countB++; tempB = tempB->next;}
Node *res, *tres;
res = new Node();
res->next = NULL;
tres = res;
for(int i = 0; i < countA+countB-1; i++)
{
Node* temp = new Node();
temp->next = NULL;
tres->next = temp;
tres = tres->next;
}
while(headA != NULL && headB != NULL)
{
if(headA->data > headB->data)
{
res->data = headB->data;
res = res->next;
headB = headB->next;
}
else if(headA->data < headB->data)
{
res->data = headA->data;
res = res->next;
headA = headA->next;
}
}
if(headA)
{
res= headA;
//res = res->next;
//headA = headA->next;
}
if(headB)
{
res = headB;
//res = res->next;
//headB = headB->next;
}
return res;
}
這次~ no response on stdout ~
NULL對於C++而言已過時 – Slava
爲什麼在合併之前需要對這些列表中的元素進行計數? – SergeyA