标准MergeSort算法

时间:2017-03-16 21:53:58

标签: algorithm sorting recursion merge mergesort

我目前正在处理一个非常标准的Merge Sort文件,但是我遇到了一些问题。我对数据结构很新,所以不要完全理解发生了什么。任何提示都会很好。感谢。

这是代码

#include <stdio.h>
#include <stdlib.h>

typedef struct CELL *LIST;
struct CELL {
    int element;
    LIST next;
}

LIST merge(LIST list1, LIST list2);
LIST split(LIST list);
LIST MergeSort(LIST list);
LIST MakeList();
void PrintList(LIST list);

int main()
{
    LIST list;

    list = MakeList();
    PrintList(MergeSort(list));
}

LIST MakeList()
{
    int x;
    LIST pNewCell;
    if(scanf("%d", &x) == EOF) return NULL;
    else {
        pNewCell = (LIST) malloc(sizeof(struct CELL));
        pNewCell->next = MakeList();
        pNewCell->element = x;
        return pNewCell;
    }
}

void PrintList(LIST list)
{
    while(list != NULL) {
        printf("%d\n", list->element);
        list = list->next;
    }
}

LIST MergeSort(LIST list)
{
    LIST SecondList;

    if (list == NULL) return NULL;
    else if (list->next == NULL) return list;
    else {
        SecondList = split(list);
        return merge(MergeSort(list), MergeSort(SecondList));
    }
}

LIST merge(LIST list1, LIST list2)
{
    if (list1 == NULL) return list2;
    else if(list2 == NULL) return list1;
    else if(list1->element <= list2->element){
        list1->next = merge(list1->next, list2);
        return list1;
    }
    else {
        list2->next = merge(list1, list2->next);
        return list2;
    }
}

LIST split(LIST list)
{
    LIST pSecondCell;

    if (list == NULL) return NULL;
    else if (list->next == NULL) return NULL;
    else {
        pSecondCell = list->next;
        list->next = pSecondCell->next;
        pSecondCell->next = split(pSecondCell->next);
        return pSecondCell;
    }
}

我得到的错误(在多个平台上)是

prog.c:10:6: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘merge’
 LIST merge(LIST list1, LIST list2);
      ^~~~~
prog.c: In function ‘MergeSort’:
prog.c:53:16: warning: implicit declaration of function ‘merge’ [-Wimplicit-function-declaration]
         return merge(MergeSort(list), MergeSort(SecondList));
                ^~~~~
prog.c:53:16: warning: return makes pointer from integer without a cast [-Wint-conversion]
         return merge(MergeSort(list), MergeSort(SecondList));
                ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
prog.c: At top level:
prog.c:57:6: error: conflicting types for ‘merge’
 LIST merge(LIST list1, LIST list2)
      ^~~~~
prog.c:53:16: note: previous implicit declaration of ‘merge’ was here
         return merge(MergeSort(list), MergeSort(SecondList));
                ^~~~~

1 个答案:

答案 0 :(得分:0)

这是错误的:

typedef struct CELL *LIST;
struct CELL {
    int element;
    LIST next;
}

请改为尝试:

typedef struct CELL {
    int element;
    struct CELL *next;
} CELL, *LIST;

请注意next必须是指针,而不是另一个CELL结构。

您的第一条错误消息只是指出您在声明struct CELL后错过了分号。 (这也是merge()声明被忽视的原因。)