Mi sto esercitando per un esame con questo esercizio:
"Si consideri il seguente tipo:
typedef struct EStr {
char * str; //stringa allocata dinamicamente
struct EStr *next;
} EStr, *LStr;
Scrivere una funzione void inscat(LStr L) che per ogni coppia di elementi consecutivi della lista L che hanno stringhe uguali inserisce un nuovo elemento tra di essi la cui stringa è la concatenazione delle stringhe dei due elementi. Esempio:
L = "A" → "A" → "B" -> "B" → "B"
Dopo inscat(L), L = "A" → "AA" → "A" → "B" → "BB" → "B" → "BB" → "B"
"
Ho scritto questo codice:
codice:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
typedef struct EStr{
char *str;
struct EStr *next;
}EStr,*LStr;
void inscart(LStr l);
void visualizza(LStr t);
void svuota(LStr t);
LStr insord(LStr t);
int main (int argc, const char * argv[]){
LStr t=NULL;
printf("\nRiempi la lista:\n");
t=insord(t);
printf("\nQuindi la lista è:\n");
visualizza(t);
if(t!=NULL){
inscart(t);
printf("\nLa nuova lista è:\n");
visualizza(t);
}
else
printf("\nERROR LIST EMPTY\n");
if(t!=NULL)
svuota(t);
return 0;
}
void inscart(LStr l){
while(l!=NULL){
LStr prec=l;
LStr succ=l->next;
if(l->str==succ->str){
char *string=malloc(sizeof(char)*(strlen(l->str)+1));
strcat(string,l->str);
string=realloc(string,(strlen(succ->str)+1));
strcat(string,succ->str);
LStr new=(EStr*)malloc(sizeof(EStr));
new->str=strcpy(new->str,string);
new->next=succ;
prec->next=new;
}
l=l->next;
}
}
void svuota(LStr t){
LStr temp;
printf("\nErase elements: ");
if(t!=NULL){
do {
printf("|%s| ",t->str);
temp=t;
t=t->next;
free(temp);
}while(t!=NULL);
printf("\nList empty\n");
}
else
printf("\nThe list is already empty!\n");
}
void visualizza(LStr t){
LStr p;
printf("\nHead ");
p=t;
while(p!=NULL){
printf("|%s| ",p->str);
p=p->next;
}
printf("Tail\n");
}
LStr insord(LStr t){
int scelta;
do{
char *valore=malloc(10*sizeof(char));
printf("\nInsert a new element in the list\n");
scanf("%s",valore);
LStr nuovo=(EStr*) malloc(sizeof(EStr));
nuovo->str=malloc(sizeof(char)*(strlen(valore)+1));
nuovo->str=strcpy(nuovo->str,valore);
nuovo->next=NULL;
LStr temp,prec; //puntatori per confronti
if(t==NULL)
t=nuovo;
else { //else 1
if(t->str>=nuovo->str) { //if 1
temp=t;
t=nuovo;
t->next=temp;
}//chiusa if 1
else { //else 2
temp=t;
while(temp!=NULL && nuovo->str>=temp->str) { //while
prec=temp;
temp=temp->next;
}//chiusa while
nuovo->next=temp;
prec->next=nuovo;
} //chiusa else 2
} //chiusa else 1
printf("\nDo you want to continue the insertion? 0=yes 1=no\n");
scanf("%d",&scelta);
}while(scelta==0);
return t;
}
I valori vengono inseriti correttamente nella lista, ma quando si arriva nella funzione void inscart(LStr l) il programma si blocca nell'IF poichè la lista "l" passata alla funzione punta all'ultimo elemento della lista, quindi quando va a fare il confronto trova che "succ" è null. Perchè la lista passata punta all'ultimo elemento e non al primo??