Interlink a chained list in c

Asked

Viewed 438 times

1

Hello I’m trying to do an exercise where I need to interlink 2 chained lists. But my function is only returning a number only. The function is the intercale();

insira o código aqui
#include <stdio.h>
#include <stdlib.h>

typedef struct LISTA{
    int dado;
    struct LISTA *prox;
} lista;

typedef struct LISTA2{
    int dado;
    struct LISTA2 *prox;
} lista2;

lista *insere(lista *p, int valor){ 
    lista *novo;
    novo=(lista*)malloc(sizeof(lista));
    novo->dado = valor;
    novo->prox = p;
    return novo;        
}

void imprime(lista *l){
    lista *p = l;
    for(p = l; p != NULL; p=p->prox){
        printf("%d-",p->dado);
    }
}

lista* intercala (lista* l, lista2* l2){    
    lista *li = (lista*)malloc(sizeof(lista));
    lista *p1;
    lista2 *p2;

    for(p1 =l, p2 =l2; p1!= NULL && p2!=NULL; p1 =p1->prox, p2=p2->prox){
        li->dado = p1->dado;
        li->prox = p1->prox;
        li->dado = p2->dado;
        li->prox = p2->prox;
    }
    return li;
}

main(){     
    lista *l;
    lista2 *l2;
    l  = NULL;
    l2 = NULL;

    l = insere(l, 1);
    l = insere(l, 2);
    l = insere(l, 3);
    imprime(l);
    printf("\n");
    l2 = insere(l2, 4);
    l2 = insere(l2, 5);
    l2 = insere(l2, 6);
    imprime(l2);
    printf("\n");
    //concatena(l,l2);
    //imprime(l);
    l =intercala (l,l2);
    imprime(l);
}
  • 1

    To interlink you need to allocate memory in the new lista the size of L1 + L2

  • Something like that ? list li = (list)malloc(sizeof(list)+ sizeof(Lista2))

  • In the list structure it should have the size of each list, then tamanho * sizeof(lista)

  • I made 2 global variables to get the size and then I added them within the scope but it still didn’t work. I think it’s the function that is wrong

  • I have already commented on another question of yours and I repeat, its implementation is weak, I warned that later to use in other functions would give problem, I suggested to see the lista I implemented on Github

  • This implementation was the one that I was taught in college, this semester so it will be kind of hard to assimilate differently because I’m still learning chained lists maybe forward I can solve better.

Show 1 more comment
No answers

Browser other questions tagged

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