首页 > 解决方案 > 如何反转链表

问题描述

我正在尝试反转返回反转列表的链接列表。

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;
        }

}

这是一个好主意吗 ?

标签: c

解决方案


首先,在这种情况下,对 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;

推荐阅读