How to clone a list linked in c?

Asked

Viewed 545 times

6

How can I make a linked list without being recursive, I have this so far.

Code:

typedef struct slist *LInt;

typedef struct slist {
    int valor;
    LInt prox;
}Nodo;



LInt clone (LInt a) {
    LInt k;
    if(a==NULL) {return NULL;}
    else {
        while(a!=NULL) {
            k=(LInt)malloc(sizeof(Nodo));
            k->valor=a->valor;
            a=a->prox;
            k->prox=a;
        }
        return k;
    }
}

Whoever can help, I appreciate it. Thank you

  • I believe that what is missing, of its structure, is to save the "head". Then, in the first step you head->value = a-> value; head->Prox = a->Prox; And then iterate with the rest of the list (using k as an auxiliary) and return the head

  • What exactly do you mean by "without being recursive"?

1 answer

2

From what I understand, nonrecursive is in a function where there is no call of itself. So, it would be something like this:

#include <stdlib.h>
typedef struct
{
    int valor;
    void* proximo; //semelhante a "lista* proximo"
} lista;

lista* lista_construir()
{
    lista* ptr = (lista*)malloc(sizeof(lista));
    (*ptr).proximo = 0;
    (*ptr).valor = 0;
    return ptr;

}
lista* lista_ampliar(lista* lista_, unsigned int tamanho)
{
    if(tamanho == 0) return lista_;
    for(unsigned int i = 0; i < tamanho; i++)
        (*(lista_ + i)).proximo = lista_construir();
    return lista_;
}

unsigned int lista_tamanho(lista* lista_)
{
    unsigned int tamanho = 1;
    lista* copia = lista_;
    while(copia->proximo != 0)
    {
        tamanho++;
        copia = copia->proximo;
    }
    return tamanho;
}
lista* lista_clonar(lista* lista_)
{
    lista* ret = lista_construir();
    lista_ampliar(ret, lista_tamanho(lista_) - 1);
    lista* endereco_ret = ret; //endereço primordial

    lista* copia_lista = lista_;
    while(1)
    {
        ret->valor = copia_lista->valor;
        if(copia_lista->proximo == 0)
        return endereco_ret;
        else
        {
            if(ret->proximo == 0)
                exit(-1);
            else
                ret = ret->proximo;
                copia_lista = copia_lista->proximo;
            continue;
        }
    }
}

int main()
{
    lista* lista_ = lista_construir();
    lista_->valor = 1;
    lista_ampliar(lista_, 1);
    ((lista*)lista_->proximo)->valor = 2;

    lista* clone = lista_clonar(lista_);

    return (lista_->valor != clone->valor) && (((lista*)(lista_->proximo))->valor != ((lista*)(lista_->proximo))->valor); //Deve retornar 0
}

The concept is just to follow the pointers until we get to where we have to go (null pointer). Note that when dealing with memory "in management" (attempt to speak in Portuguese Managed memory), we should check all cases for anything wrong to occur; therefore, all pointers should be tested before the programmer’s immediate use.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.