所以,当我试图删除列表的第一个元素时,我遇到了这个问题。奇怪的是,我可以使用此功能直到列表中的三个元素,之后我的终端停止回答。有什么想法吗?
typedef struct event_t
{
double time;
char description[50];
int id_origin, id_dest;
struct event_t *prox;
} event_t;
void
event_remove_first (event_t ** list)
{
event_t *aux = *list;
if (*list == NULL)
printf ("Empty list\n");
else
*list = aux->prox;
free (aux);
}
bool event_add_end (event_t **list, double time, char description[], int id_origin, int id_dest) {
event_t *newelement = (event_t*)malloc(sizeof(event_t));
event_t *aux = *list, *prev = NULL;
if (newelement!=NULL) {
newelement->time = time;
strcpy (newelement->description, description);
newelement->id_origin = id_origin;
newelement->id_dest = id_dest;
newelement->prox = NULL;
if (*list==NULL)
*list = newelement;
else {
while (aux!=NULL) {
prev = aux;
aux = aux->prox;
}
prev->prox = newelement;
}
return true;
}
else {
return false;
}
}
bool event_add_ordely (event_t **list, double time, char description[], int id_origin, int id_dest) {
event_t *newelement = (event_t*)malloc(sizeof(event_t));
event_t *aux = *list, *prev = NULL;
if (newelement!=NULL) {
newelement->time = time;
strcpy (newelement->description, description);
newelement->id_origin = id_origin;
newelement->id_dest = id_dest;
if (*list==NULL) {
*list = newelement;
newelement->prox = NULL;
} else if (aux->prox == NULL) {
if (aux->time <= time) {
aux->prox = newelement;
newelement->prox = NULL;
} else {
*list = newelement;
newelement->prox = aux;
}
} else {
while (aux->time<=time) {
prev = aux;
aux = aux->prox;
}
newelement->prox = aux;
prev->prox = newelement;
}
return true;
}
else {
return false;
}
}
event_t *event_ordely (event_t *list) {
event_t *newlist = NULL;
while (list!=NULL) {
event_add_ordely (&newlist, list->time, list->description, list->id_origin, list->id_dest);
list = list->prox;
}
return newlist;
}
int main (int argc, char *argv[]) {
event_t *list = NULL, aux;
int number, i;
printf ("Digite o números de eventos: "); // Here I scan the infos of each element - its in portuguese.
scanf ("%d", &number);
printf ("\n");
for (i=0; i<number; i++) {
printf ("Evento %d\n", i+1);
printf ("Digite o tempo de duração: ");
scanf ("%lf", &aux.time);
printf ("Digite a descrição: ");
scanf ("%s", aux.description);
printf ("Digite a id de origem: ");
scanf ("%d", &aux.id_origin);
printf ("Digite a id de destino: ");
scanf ("%d", &aux.id_dest);
printf ("\n");
event_add_end (&list, aux.time, aux.description, aux.id_origin, aux.id_dest);
}
event_t *newlist = event_ordely (list);
event_remove_first (&newlist);
return 0;
}
答案 0 :(得分:0)
试试我的代码。解释在代码中:
void event_remove_first (event_t ** list)
{
event_t *aux = *list;
if (*list == NULL)
{
printf ("List is already empty\n");
return;
}
// there is only one object which will be deleted
if(*list->prox == NULL)
{
printf ("List got empty\n");
free (*list);
*list = NULL;
return;
}
*list = aux->prox;
free (aux);
}