合并排序的链表列表

时间:2019-03-01 00:30:24

标签: c++ recursion linked-list mergesort

im试图合并排序数组的每个元素,而数组是链表的头。

//for each element in array
for(int i=0; i<MAX_SIZE; i++){

    //NOTE: this current element (i) holds a linked list...sort it

    //merge function should accept head of linked list which is this element
    mergeSort(&inventory[i]);

}

以下是我的归并排序函数,它递归地调用自己....

void mergeSort(data** A){

data* head = *A;  //head is begining of A
data* r;
data* l;


//base case ... if linked list length is 0 or 1
if(head == nullptr || head->next == nullptr){
    return;
}

//divide linked list into halves
split(head, &r, &l);

//r holds first half of linked list
//l holds left second half of linked list

mergeSort(&r);
mergeSort(&l);
*A = merge(r,l);  //merge into linked list A
}

下面是分割算法...

void split(data* source, data** R, data** L){ //source is head of this linked list

data* slow = source;
data* fast = source->next;

while(fast->next->next){ //while fast has two nodes after it  
    fast= fast->next;
    slow = slow->next;
}


*L = source;
*R = slow->next;
slow->next = nullptr;
}

最后我将这些段合并到链表A中,下面的函数返回该链表的标题并设置为A ...

data* merge(data* R, data* L){

data* result = nullptr;


//base cases
if(R == nullptr){
    return R;
}
else if(L == nullptr){
    return L;
}

if(R->pnum <= L->pnum){
    result = R;
    result->next = merge(R->next, L);
}
else{
    result = L;
    result->next = merge(L, R->next);
}

return result;

}

当我尝试使用简单的打印功能打印整个阵列时,代码成功运行,但没有任何输出,我认为合并代码永远不会停止运行。终端中没有错误显示(使用xcode)。

有关如何解决此问题的任何建议?谢谢!

1 个答案:

答案 0 :(得分:0)

请尝试使用此合并排序代码。

printf("%p\n", (void*) (&a[0] + 1));  // next `int` address
printf("%p\n", (void*) (&a + 1));     // one past end of array address

Source