我需要帮助我的合并排序功能,这是名称的链接列表。当我运行这个程序的时候,我得到了一个隔离错误,我感觉有些地方不对。提前感谢您的帮助。
程序应该在排序前打印出名称列表,然后在排序后打印出名称列表。
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
#define MAX_STR_LEN 25
typedef struct Data_ {
char *name;
struct Data_ *next;
}Data;
void split_in_half(Data *source, Data **frontRef,Data **backRef);
Data* merge(Data *a, Data *b);
void merge_sort(Data **list);
Data* read_from_file(const char* file, const int size);
void display(Data *list);
void push(Data **head, char *name);
int main(int argc, char **argv){
if(argc != 2){
printf("Not enough parameters!");
exit(0);
}
Data *head = NULL;
int size = 10;
head = read_from_file(argv[1], size);
printf("nBefore sort");
display(head);
printf("nMerge Sortn");
merge_sort(&head);
display(head);
}
void merge_sort(Data **list){
Data *head = *list;
Data *temp;
Data *temp2;
if((head == NULL) || (head->next == NULL))
{
return;
}
split_in_half(head, &temp, &temp2);
head = merge(temp, temp2);
}
Data *merge(Data *a, Data *b){
Data *result = NULL;
if(a == NULL)
return(b);
else if(b==NULL)
return (a);
if(strcmp(a->name, b->name) > 0)
{
result = a;
result->next = merge(a->next, b);
}
else
{
result = b;
result->next = merge(a, b->next);
}
return (result);
}
void split_in_half(Data *source, Data **frontRef,Data **backRef){
Data *fast;
Data *slow;
if(source == NULL || source->next == NULL)
{
*frontRef = source;
*backRef = NULL;
}
else
{
slow = source;
fast = source->next;
while(fast != NULL)
{
fast = fast->next;
if(fast != NULL)
{
slow = slow->next;
fast = fast->next;
}
}
}
*frontRef = source;
*backRef = slow->next;
slow->next = NULL;
}
void push(Data **head, char *name){
Data *temp = malloc(sizeof(Data));
temp->name = strdup(name);
temp->next = *head;
*head = temp;
}
Data* read_from_file(const char* file, const int size){
FILE *input;
input = fopen(file, "r");
Data *new_ = (Data*)malloc(sizeof(Data*));
new_->next = NULL;
int i;
char name[MAX_STR_LEN];
for(i = 0; i < size; i++){
fscanf(input, "%24s", &name);
push(&new_, name);
}
return new_;
}
void display(Data *list){
Data *current = list;
while(current->next != NULL){
printf("n%s", current->name);
current = current->next;
}
}
我读进去的文件是一个名字列表。它是:
德里克德鲁Randell
特雷卡门科林
艾迪Pablo拉蒙特
Dexter在read_from_file中有:
Data *new_ = (Data*)malloc(sizeof(Data*));
new_->next = NULL;
但是,您只为指针分配了空间,而没有为数据结构分配空间。因此,您将在上面的第二行中写掉已分配空间的末尾。
相反,写:
Data *new_ = (Data*)malloc(sizeof(Data));
new_->next = NULL;
[你可以在Do I cast the result of malloc中了解到强制转换malloc结果的缺点。,但我只是为上面的进展做了最小的改变]
一旦您完成了上面的修复,请尝试在调试器中遍历程序,或者添加printf语句,这样您就可以准确地看到程序的行为,并了解在哪里出现了任何其他问题。