0
Hey, guys, I need help copying a list just chained up backwards. For example, if the original list is 1->2->3->null, I need it to be 3->2->1->null.
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
typedef int bool;
enum { false, true };
// elemento da lista
typedef struct estr {
char letra;
struct estr *prox;
} NO;
typedef struct {
NO *inicio;
} LISTA;
void inicializarLista(LISTA *l) {
l->inicio = NULL;
}
void criarLista(LISTA *l, char plvr[]) {
NO *ult = NULL;
for (int i = 0; i < strlen(plvr); i++) {
NO *novo = (NO *) malloc(sizeof(NO));
novo->letra = plvr[i];
novo->prox = NULL;
if (ult) {
ult->prox = novo;
} else {
l->inicio = novo;
}
ult = novo;
}
}
void imprimirLista(LISTA l) {
NO *p = l.inicio;
while(p) {
printf("%c", p->letra);
p = p->prox;
}
}
LISTA* clonarLista(LISTA* l){
NO novo = NULL;
LISTA* resp = novo; //inicializar lista resp
while(l){
novo = (NO *) malloc(sizeof(NO));
novo->letra = l->letra;
novo->prox = NULL;
l = l->prox;
}
return resp;
}
void inverter(LISTA* resp){
NO* ant = NULL;
NO* atual = //inicio da lista resp
NO* seg; //seguinte
while (atual){
seg = atual->prox;
atual->prox = ant;
ant = atual;
atual = atual->prox;
}
//inicio da lista resp = ant;
}
int main() {
LISTA l;
LISTA resp;
inicializarLista(&l);
inicializarLista(resp);
char palavra[] = "caio";
criarLista(&l, palavra);
inverter(&resp)
imprimirLista(resp);
return 0;
}
Isac, the problem lies in the fact that in your solution a new list has not actually been created. I mean, through Malloc.
– Kfcaio
@Caio_ignatz In his original logic he also did not have
malloc
, and so I deduced that I wanted to invert the list that is received as a parameter in the functioninverter
, and not create a new inverted. But I don’t know if I’m getting what you’re saying correctly, try to be a little more specific.– Isac
first, I need to copy the received list. Second, I need to create a new list from the inversion of the received list. I wasn’t clear on that point.
– Kfcaio
@Caio_ignatz I already edited in this sense, I calculated that this is what I wanted due to the cloning function.
– Isac
It worked, Isac. Thank you very much! You helped a lot. Now I’m going to study your code
– Kfcaio
@Caio_ignatz No problem, good study.
– Isac