Insert second node in front of the first

0

I have a small code where I want to insert a node at the beginning of the list, but it is placed after the first node I already have: For example pointer first points to NULL, the list is empty, I insert the first node with value 5, So all right, but adding a new node with value 7 and remain in display 75 is upside down, 57, when I'm indicating that the new node points to the existing node and it to NULL, I do not understand why it happens. I leave the code:

primero=NULL;
nodo1 = (t_nodo*)malloc(sizeof(t_nodo));
nodo1->dato=5;
nodo1->siguiente=NULL;
primero=nodo1;
printf("%d",nodo1->dato);

nodo2 = (t_nodo*)malloc(sizeof(t_nodo));
nodo2->dato=7;
nodo2->siguiente=nodo1;
primero=nodo2;
printf("%d",nodo2->dato);

It should be displayed first on 7 and then on 5. Thanks in advance

    
asked by Mario Guiber 08.08.2017 в 18:59
source

1 answer

1
printf("%d",nodo1->dato);
// ...
printf("%d",nodo2->dato);

That code is showing the elements regardless of their order in the list.

What you have to do is iterate the list after filling it and print the values that you find

t_nodo* ptr = primero;

while( ptr )
{
  printf("%d",ptr->dato);
  ptr = ptr->siguiente;
}
    
answered by 08.08.2017 / 19:11
source