gpt4 book ai didi

c++ - 无法使用辅助链表合并排序链表

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:21:58 26 4
gpt4 key购买 nike

请给出问题的简单解决方案。我使用了像 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

最佳答案

在您的代码中发现了两个问题。首先,应该在两个地方将等于运算符更改为 bool 值:

if (flag = 0){

应该是

if (flag == 0){

那么,遍历这两个链表的时候要保留一个尾节点。

我转换了这里的代码(应用最小的更改),它有效:

ListNode* mergeTwoLists(ListNode* A, ListNode* B) {

ListNode* head;
ListNode* tail; //<-- a tail is introduced
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){ //<-- fixed
head = root;
tail=head;
flag = 1;
}
else
{
tail->next=root;
tail = root;
}


//root->next = el;
//root = root->next;
H1 = H1->next;
}else{
root = new ListNode(H2->val);
if (flag == 0){ //<-- fixed
head =root;
tail=head;
flag = 1;
}
else
{
tail->next=root;
tail = root;
}
//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;
tail->next=root;
tail=root;
// root = root->next;
H2 = H2->next;
}
while (H1 != NULL){
root = new ListNode(H1->val);
//cout << root->val << " ";
//root->next = el;
tail->next=root;
tail=root;
//root = root->next;
H1 = H1->next;
}

ListNode *start=head;
while(start)
{
cout<<start->val<<" ";
start=start->next;
}


return head;
}

关于c++ - 无法使用辅助链表合并排序链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40690189/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com