I have this code:
#include "stdlib.h"
#include "stdio.h"
typedef struct lista TLista;
struct lista{
char dado;
TLista* prox;
}lista;
TLista* insere(TLista* l, char dado){
TLista* aux;
TLista* anterior;
if(l == NULL){
l = (TLista*) malloc(sizeof(TLista));
l->dado = dado;
l->prox = NULL;
}else{
aux = l;
while(aux != NULL){
anterior = aux;
aux = aux->prox;
}
aux = (TLista*) malloc(sizeof(TLista));
anterior->prox = aux;
aux->dado = dado;
aux->prox = NULL;
}
return l;
}
void imprime(TLista* l){
if(l == NULL){
printf("A lista esta vazia");
}else{
while(l != NULL){
printf("%c", l->dado);
l = l->prox;
}
}
void concatena(TLista* lista1, TLista* lista2){
TLista* aux = lista1;
if(!lista1){
lista1 = lista2;
printf("\nInside function: ");
imprime(lista1);
}else{
while(aux->prox != NULL){
aux = aux->prox;
}
aux->prox = lista2;
}
}
int main() {
TLista* lista1 = NULL;
TLista* lista2 = NULL;
printf("\n");
lista1 = insere(lista1, 't');
lista1 = insere(lista1, 'e');
lista1 = insere(lista1, 's');
lista1 = insere(lista1, 't');
lista1 = insere(lista1, 'e');
imprime(lista1);
printf("\n\n\n\n");
lista2 = insere(lista2, 'x');
lista2 = insere(lista2, 'u');
lista2 = insere(lista2, 'l');
lista2 = insere(lista2, 'a');
lista2 = insere(lista2, 'm');
lista2 = insere(lista2, 'b');
lista2 = insere(lista2, 's');
concatena(lista1,lista2);
printf("\nOutside function: ");
imprime(lista1);
printf("\n\n");
return 0;
}
Function names were written in Portuguese. Thus, the function concatenashould combine the two lists, and in fact it does this when lista1it is not NULL, but when I comment on these lines:
lista1 = insere(lista1, 't');
lista1 = insere(lista1, 'e');
lista1 = insere(lista1, 's');
lista1 = insere(lista1, 't');
lista1 = insere(lista1, 'e');
imprime(lista1);
the function concatenashould get the first list as NULL, and the second how xulambs. Accordingly, it lista1should get the address of lista2head, but when the function completes, it is lista1empty.
I debugged printing values lista1right after getting the header lista2, and it works fine, but when it comes to the main function, lista1still NULL.
Can someone help me figure out what's going on? thank
Multiple translations:
- lista = list
- dado = datali >
- prox = next
- imprime = print
- insere = add
- concatena = merge