【发布时间】:2017-04-03 01:52:52
【问题描述】:
请给出一个简单的解决问题的方法。我使用了类似 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
【问题讨论】:
-
如果我能提供更多信息,请告诉我
标签: c++ algorithm pointers linked-list mergesort