How to make a clone from a linked list in c?

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

Who can help, I am grateful. Thanks

    
asked by anonymous 22.04.2015 / 21:05

1 answer

2

From what I understand, non-recursive is in a function where there is no call of itself. So it would look 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 go following the pointers until you get to where we have to get (null pointer). Note that when we deal with memory "in management" (attempt in Portuguese to speak managed memory ), we must check all cases for nothing wrong to occur; so all pointers should be tested before the immediate use of the programmer.

    
26.04.2015 / 23:27