【发布时间】:2020-09-25 12:11:38
【问题描述】:
我正在尝试对链表进行合并排序。
我将 head 变量保持为全局变量并应用基本算法,即分而治之。
我不明白为什么会出现分段错误。
我知道我可以通过传递 head 作为参考来做到这一点,但我仍然需要知道为什么会这样。
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node *next;
};
Node *head;
void push(Node **head_ref, int x) {
Node *temp = new Node();
temp->next = *head_ref;
temp->data = x;
*head_ref = temp;
}
void split(Node *temp, Node **a, Node **b) {
Node *slow;
Node *fast;
slow = temp;
fast = temp->next;
while (fast != NULL) {
fast = fast->next;
if (fast != NULL) {
slow = slow->next;
fast = fast->next;
}
}
*a = temp;
*b = slow->next;
slow->next = NULL;
}
Node *mergesort(Node *a, Node *b) {
if (a == NULL) {
return b;
} else
if (b == NULL) {
return a;
}
if (a->data < b->data) {
a->next = mergesort(a->next, b);
return a;
} else {
b->next = mergesort(a, b->next);
return b;
}
}
void merge(Node **head_ref) {
Node *head = *(head_ref);
Node *a;
Node *b;
if (head == NULL || head->next == NULL) {
return;
}
split(head, &a, &b);
merge(&a);
merge(&b);
head = mergesort(a, b);
}
void print(Node *n) {
while (n != NULL) {
cout << n->data << " ";
n = n->next;
}
}
我的主要方法如下:
int main() {
Node *head;
push(&head, 1);
push(&head, 3);
push(&head, 6);
push(&head, 4);
push(&head, 2);
print(head);
merge(&head);
cout << endl;
print(head);
}
【问题讨论】:
-
您可以通过点击分数下方的灰色复选标记来接受答案。
标签: c++ linked-list mergesort divide-and-conquer