Your problem is in the internal logic that you are using. Let's analyze in detail your do ... while
loop:
do
{
scanf( "%d", &dato );
list->dato = dato;
list->siguiente = (lista *)malloc( sizeof( struct nodo ) );
list = list->siguiente;
}while( getchar( ) != 10 );
list->siguiente = NULL;
You read the keyboard data.
You save it in the current node.
You create a new empty node (without initializing).
You advance your pointer to that new node that you have created.
If the user presses ENTER , you end the loop.
Look closely. You end the loop leaving the last node uninitialized .
One possible solution would be to use an auxiliary variable, so as not to lose sight of the previous node. As you can see, I have also changed the way to finish the data entry: in my system, your solution with getchar( )
does not work; Now, you have to enter a letter to finish.
#include <stdio.h>
#include <stdlib.h>
typedef struct nodo {
int dato;
struct nodo *siguiente;
}lista;
int main( void ) {
int dato;
lista *list = malloc( sizeof( lista ) );
lista *aux = list;
lista *prev = list;
printf( "Ingresa datos enteros (una letra para terminar):\n");
while( scanf( "%d", &dato ) ) {
list->dato = dato;
prev = list;
list->siguiente = malloc( sizeof( lista ) );
list = list->siguiente;
};
if( aux == list ) {
printf( "¡ La lista está vacía !\n" );
free( aux );
aux = NULL;
} else {
free( prev->siguiente );
prev->siguiente = NULL;
}
while( aux ) {
printf( "%p: %d\n", aux, aux->dato );
aux = aux->siguiente;
}
return 0;
}
There is an extra part, just after the while( )
, which is responsible for controlling the correction of the list: if it is empty, it indicates it, and if it is not empty, it eliminates the last node and appropriately places the pointer siguiente
in the penultimate node.