請給出一個簡單的問題解決方案。我已經使用了像mergesort這樣的算法,但我無法返回我創建的輔助鏈接列表的頭部。我已經看到了堆棧溢出的其他例子。但我想知道我的代碼問題在哪裏。無法使用輔助鏈接列表合併排序的鏈接列表
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
ListNode* Solution::mergeTwoLists(ListNode* A, ListNode* B) {
ListNode* head;
ListNode* root;
ListNode* H1 = A;
ListNode* H2 = B;
int flag = 0;
while (H1 != NULL && H2 != NULL){
if(H1->val < H2->val){
root = new ListNode(H1->val);
//cout << root->val << " ";
if (flag = 0){
head = root;
flag = 1;
}
//root->next = el;
root = root->next;
H1 = H1->next;
}else{
root = new ListNode(H2->val);
if (flag = 0){
head =root;
flag = 1;
}
//cout << root->val << " ";
//root->next = el;
root = root->next;
H2 = H2->next;
}
}
while (H2 != NULL){
root = new ListNode(H2->val);
//cout << root->val << " ";
//root->next = el;
root = root->next;
H2 = H2->next;
}
while (H1 != NULL){
root = new ListNode(H1->val);
//cout << root->val << " ";
//root->next = el;
root = root->next;
H1 = H1->next;
}
ListNode *start=head;
while(start)
{
cout<<start->val<<" ";
start=start->next;
}
return head;
}
我已經使用cout知道順序,它給出了正確的順序。我在這裏錯過了一些東西。沒有列表爲NULL
讓我知道如果我能進一步信息 –