0
I started making a chained list program, but when I use the print function, it wasn’t printing anything, so I discovered that the LISTA
after leaving the function inserts, it again has the value NULL
and I don’t know why.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int num;
struct Node *prox;
};
typedef struct Node node;
node* aloca();
void inicia(node *LISTA);
void insere(node *LISTA, int val);
void imprime(node *LISTA);
int main(void) {
node *LISTA = NULL;
inicia(LISTA);
insere(LISTA, 10);
insere(LISTA, 20);
insere(LISTA, 5);
imprime(LISTA);
return 0;
}
node* aloca() {
node *LISTA = (node *)malloc(sizeof(node));
return(LISTA);
}
void inicia(node *LISTA) {
LISTA = NULL;
}
void insere(node *LISTA, int val) {
node *p1 = aloca();
node *p2;
p1->num = val;
p1->prox = NULL;
if (LISTA == NULL) {
LISTA = p1;
}else {
p2 = LISTA;
while (p2->prox != NULL) {
p2 = p2->prox;
p2->prox = p1;
}
}
}
void imprime(node *LISTA) {
node *tmp;
tmp = LISTA;
while(tmp != NULL) {
printf("\nasfdsdf");
printf("%d", tmp->num);
tmp = tmp->prox;
}
}
The problem is the return of the same pointer. Then I see if there are other errors, I need to leave quickly.
– Maniero
In function
insere
has a while that seems suspicious to me. You start walking through the list and insert the item right in the first iteration. I think the correct one would be to move thatp2->prox = p1;
for after the while.– jlHertel
@jHertel Well noted, but only optimized the code, does not solve the problem :(
– Bruno Casas
@Brunocasas Any of the answers solved your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).
– Maniero