I have a problem with the following program. This consists of adding elements to a linked list in an increasing way, that is, the elements will be sorted in the list from least to greatest, with the lowest value being the "head" of the list and the one with the highest value. in the last node, which should point to NULL.
The problem is that, by calling the showDataList function, which shows all the elements added to the list, making a tour through each node until finding the NULL value, it gives me an infinite impression of (I believe) the following memory addresses to which the last node points, and because it is not NULL, they are printed constantly.
Therefore, my question is, how could I modify the program in such a way that the last node of my list points to NULL, and in this way, I could only print the values added to my list?
Note: In the main function I added a test in which I entered values to the function enter data and then I show them explicitly, without using the function showData, to verify that the values have been saved in the list.
I hope you can help me.
#include <stdio.h>
#include <stdlib.h>
struct elementos
{
int dato;
struct elementos *siguiente;
};
typedef struct elementos Nodo;
void ingresarValor(Nodo **cabeza, int valor);
void mostrarDatosLista(Nodo *cabeza);
int main()
{
int valor;
Nodo *primero = (Nodo*)malloc(sizeof(Nodo));
primero = NULL;
ingresarValor(&primero, 2);
ingresarValor(&primero, 4);
ingresarValor(&primero, 3);
ingresarValor(&primero, -1);
ingresarValor(&primero, 6);
printf("%d\n", primero -> dato);
primero = primero -> siguiente;
printf("%d\n", primero -> dato);
primero = primero -> siguiente;
printf("%d\n", primero -> dato);
primero = primero -> siguiente;
printf("%d\n", primero -> dato);
primero = primero -> siguiente;
printf("%d\n", primero -> dato);
primero = primero -> siguiente;
//mostrarDatosLista(primero);
return 0;
}
void ingresarValor(Nodo **cabeza, int valor)
{
Nodo *nuevo_Nodo = (Nodo*)malloc(sizeof(Nodo));
nuevo_Nodo -> dato = valor;
nuevo_Nodo -> siguiente == NULL;
if(*cabeza == NULL)
{
*cabeza = nuevo_Nodo;
}
else if(nuevo_Nodo -> dato > (*cabeza) -> dato)
{
Nodo *anterior = *cabeza;
Nodo *p = *cabeza;
while(nuevo_Nodo -> dato > p -> dato)
{
anterior = p;
p = p -> siguiente;
}
anterior -> siguiente = nuevo_Nodo;
nuevo_Nodo -> siguiente = p;
}
else
{
nuevo_Nodo -> siguiente = *cabeza;
*cabeza = nuevo_Nodo;
}
}
void mostrarDatosLista(Nodo *cabeza)
{
while(cabeza != NULL)
{
printf("%8d\n", cabeza -> dato);
cabeza = cabeza -> siguiente;
}
}