鍍金池/ 問(wèn)答/C/ 為什么這段歸并排序會(huì)出錯(cuò)?

為什么這段歸并排序會(huì)出錯(cuò)?

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

typedef struct node{
    int num;
    struct node *next;
} Node;

Node* merge(Node *a,Node *b)        //對(duì)鏈表歸并
{
    Node *l1=a,*l2=b;
    Node *tmp=NULL;
    Node *temp=NULL;
    while(l1&&l2)
    {
        if(l1->num<=l2->num)
        {
            if(l1==a&&tmp==NULL)    //選擇頭節(jié)點(diǎn)
            {
                tmp=a;
                temp=tmp;
            }
            else                    //歸并
            {
                temp->next=l1;
                temp=temp->next;
            }
            l1=l1->next;
        }
        else
        {
            if(l2==b&&tmp==NULL)    //選擇頭節(jié)點(diǎn)
            {
                tmp=b;
                temp=tmp;
            }
            else                    //歸并
            {
                temp->next=l2;
                temp=temp->next;
            }
            l2=l2->next;
        }
    }
    temp->next=(l1==NULL)?l2:l1;
    return tmp;
}

Node *mergeSort(Node *a)            //鏈表歸并排序
{
    Node *temp=a;
    Node *tmp=temp;
    if(temp==NULL||temp->next==NULL) return a;
    while(temp&&temp->next)
    {
        temp=temp->next->next;
        tmp=tmp->next;
    }
    temp=tmp->next;
    tmp->next=NULL;
    return merge(mergeSort(a),mergeSort(temp));
}

int main(void)
{
    Node *a=(Node *)malloc(20*sizeof(Node));
    srand(time(NULL));
    for(int i=0;i<20;i++)
    {
        (a+i)->num=rand()%50;
        (a+i)->next=a+i+1;
    }
    a[19].next=NULL;
    for(int i=0;i<20;i++)
    {
        printf("%d ",a[i].num);
    }
    putchar('\n');

    Node *l=mergeSort(a);
    for(Node *b=l;b;b=b->next)        //運(yùn)行代碼時(shí),顯示出現(xiàn)段錯(cuò)誤
    {
        printf("%d ",b->num);
    }
    putchar('\n');

    return 0;
}

運(yùn)行這段代碼,顯示出現(xiàn)段錯(cuò)誤,希望熱心人幫我指出錯(cuò)誤。

回答
編輯回答
扯機(jī)薄
Node *mergeSort(Node *a)            //鏈表歸并排序
{
   ......
    return merge(mergeSort(a),mergeSort(temp)); //這里a并沒(méi)有變化,會(huì)不停調(diào)用,沒(méi)有遞歸的退出條件 
}
2018年2月23日 07:50