【发布时间】:2021-07-14 23:57:46
【问题描述】:
以下代码用于对链表进行合并排序。它发出分段错误。我真的不知道如何处理上述问题。我所能找到的只是我试图访问内存的受限部分,我认为我可能出错的唯一地方是在拆分函数体下拆分和排序后重新组合两个链表。如果我能从这里获得一些关于如何处理分段错误以及如何纠正它们的指导,我将不胜感激。
//Segmentation fault
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node *next;
Node(int data)
{
this->data = data;
next = NULL;
}
};
void print(Node *head)
{
Node *temp = head;
while (temp != NULL)
{
cout << temp->data << " ";
temp = temp->next;
}
}
Node *insert()
{
int data;
cin >> data;
Node *head = NULL;
Node *tail = NULL;
while (data != -1)
{
Node *n = new Node(data);
if (head == NULL)
{
head = n;
tail = n;
}
else
{
tail->next = n;
tail = tail->next;
}
cin >> data;
}
return head;
}
Node *sortedMerge(Node *h1, Node *h2)
{
// Node *fHead = NULL;
// Node *fTail = NULL;
if (!h1)
{
return h2;
}
if (!h2)
{
return h1;
}
if (h1->data < h2->data)
{
h1->next = sortedMerge(h1->next, h2);
return h1;
}
else
{
h2->next = sortedMerge(h1, h2->next);
return h2;
}
}
void split(Node *head, Node *h1, Node *h2)
{
Node *slow = head;
Node *fast = head->next;
while (fast != NULL)
{
fast = fast->next;
if (fast != NULL)
{
slow = slow->next;
fast = fast->next;
}
}
h1 = head;
h2 = slow->next;
slow->next = NULL;
}
void mergeSort_LL(Node *head)
{
Node *temp = head;
Node *h1;
Node *h2;
if ((temp == NULL) || (temp->next == NULL))
{
return;
}
split(temp, h1, h2);
mergeSort_LL(h1);
mergeSort_LL(h2);
head = sortedMerge(h1, h2);
}
int main()
{
Node *head = insert();
print(head);
cout << endl;
mergeSort_LL(head);
cout << "Sorted List is : " << endl;
print(head);
return 0;
}
【问题讨论】:
-
学习使用
gdb。这可能会帮助stackoverflow.com/questions/2876357/… -
我做到了,我什至尝试了内置的 vs 代码一。拆分函数体内的while循环是关注的领域,我尝试了几种不同的快速和慢速指针方法来找到链表的中位数,但几乎无济于事。
-
你有没有试过改变2指针的方法,看看故障是否得到解决?
-
split应该获得对 h1 和 h2 指针的 reference,否则调用者将无法取回这些更改。 -
@trincot 我现在理解这个概念了!感谢大家的时间和努力!
标签: c++ algorithm sorting linked-list