Home > other >  C clone linked list
C clone linked list

Time:12-27

I would like to ask how to modify the cloneList function to work properly? I always want to add a new element to the top of the list. I want Peter still at the top of the cloned list. I can't change the function header

typedef struct TEmployee
{
    struct TEmployee *m_Next;
    struct TEmployee *m_Bak;
    char *m_Name;
} TEMPLOYEE;


TEMPLOYEE *newEmployee (const char *name, TEMPLOYEE *next)
{
    TEMPLOYEE *n = (TEMPLOYEE*) malloc(sizeof(*next));
    
    n->m_Name = (char*) malloc(sizeof(char)*100);

    strcpy(n->m_Name, name);
    n->m_Bak = NULL;        
    n->m_Next = next;
    
    return n;
}
 
TEMPLOYEE *cloneList(TEMPLOYEE *src)
{
    TEMPLOYEE *x;
    x = NULL;
    
    TEMPLOYEE *tmp = src;
    while(tmp)
    {
        x = newEmployee(tmp->m_Name, x);
        x->m_Bak = tmp->m_Bak;
        tmp = tmp->m_Next;
    }
    
    return x;
    
}
int main ()
{
    TEMPLOYEE *a, *b;
    a = NULL;
    b = NULL;
    
    a = newEmployee("Peter",a);
    a = newEmployee("John",a);
    ...
    
    b = clone(a);
}

CodePudding user response:

I guess this could help: https://www.techiedelight.com/clone-given-linked-list/ There it is explained for C, Java and Python

  • Related