2
I am programming a chained list without head, in this program there is a remove function that aims to eliminate all the repeated integers in a list, px: taking the values 8 2 8 3 the function has to return 2 3, but this function apparently went into loop, because the execution does not end, not appearing Runtime and not to errors or warnings in the compilation. follows code:
#include<stdio.h>
#include<stdlib.h>
struct reg {
int conteudo;
struct reg *prox;
};
typedef struct reg celula;
void insere (celula **p, int x) {
celula *novo, *q;
q = *p;
novo = (celula *)malloc(sizeof(celula));
novo->conteudo = x;
if (*p == NULL) {
novo->prox = NULL;
*p = novo;
}
else {
while (q->prox != NULL)
q = q->prox;
novo->prox = q->prox;
q->prox = novo;
}
}
celula* Remove (celula *p, int x) {
celula *aq, *q, *aux;
aq = NULL;
aux = q = p;
while (aux != NULL) {
while (q->prox != NULL && q->conteudo != x) {
aq = q;
q = q->prox;
}
if (aq == NULL) p = q->prox;
else aq->prox = q->prox;
free(q);
aux = aux->prox;
}
return q;
}
void imprime (celula *p) {
celula *q;
if (p == NULL) printf ("Lista Vazia");
for (q = p; q != NULL; q = q->prox)
printf ("%d ", q->conteudo);
printf("\n");
}
int main() {
celula *lista = NULL;
celula *lst = NULL;
insere(&lista, 8);
insere(&lista, 2);
insere(&lista, 8);
insere(&lista, 3);
insere(&lista, 8);
imprime(lista);
lst = Remove(lista, 8);
imprime(lst);
return 0;
}
Its very coherent solution, the problem is that it ignores the last pointer, e.g., when I ask the exclusion of element 2, occurs the following: input: 8 2 8 3 8, output: 8 8 3, I tried to modify pointers to solve this issue , but I could not.
– Marcelo de Sousa
When you assigned
aq->prox = q->prox
in chargeelse
, he "kills" the last element on the list becauseq->prox
is null in the last element, and he assigned this null to theaq
(which is the previous/current element) :)– Gomiero
This answer solves the question problem "this function apparently looped", however, there are other problems with pointers (and algorithm) in the code
– Gomiero
I put a commented example, with a different way to implement the function. I hope it helps :)
– Gomiero