如何反向链接列表

时间:2019-03-28 19:15:39

标签: c

我正在尝试反向链接列表,并返回反向列表。

typedef struct lligada 
{

     int valor;
     struct lligada *prox;

} *LInt;

这是我的功能:

LInt reverseL (LInt l){

    LInt aux = malloc (sizeof(struct lligada));

    if(l != NULL){

            while( l -> prox != NULL){
                aux = l-> prox;
                aux -> prox = l;
                l = l-> prox;
            }


    }

    else return NULL;

    return aux;
}

能帮我吗?

我尝试这样做:

if(l != NULL){

        if(l -> prox == NULL) {
            aux = l;
        }

        else{
            while( l -> prox != NULL){
                aux = l-> prox;
                aux -> prox = l;
                l = l-> prox;
            }
            aux -> prox = l;
        }

}

这是个好主意吗?

1 个答案:

答案 0 :(得分:1)

首先,在这种情况下,对malloc的调用是无用的,这是内存泄漏。

此代码段无效,因为您在前两个元素之间创建了一个无限循环

if (l != NULL) 
{
    if (l->prox == NULL) 
    {
        aux = l;
    }
    else 
    {
        while (l->prox != NULL) 
        {
            aux = l->prox;
            aux->prox = l;
            l = l->prox;
        }
        aux->prox = l;
    }
}

您可以这样更改

LInt new_head, aux;
new_head = NULL;
while (l != NULL) 
{
    aux = l->prox;
    l->prox = new_head;
    new_head = l;
    l = aux;
}

return new_head;
相关问题