I would like to ask about the ordering of nodes in a simple linked list. I am currently having problems with sorting a simple list of a field ( int
), I want to sort the nodes by changing the relationships between them, I have tried several ways, however, as they "sort" certain nodes lose the relationship they had with another node and is out of the list. As you can see in the code, I enter the data in LIFO form (that is, the last data entered is the first one in the list and so on). Enclosed I show you the code I have so far. Could you explain how to do it and maybe see it in code?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Nodo
{
int Dat;
Nodo *Sig;
};
void InLIFO(Nodo*&,int);
void printlist(Nodo*);
void clearlist(Nodo*&);
void main()
{
Nodo *L1 = NULL;
InLIFO(L1,1);
InLIFO(L1,2);
InLIFO(L1,3);
InLIFO(L1,4);
InLIFO(L1,5);
InLIFO(L1,6);
printlist(L1);
clearlist(L1);
system("PAUSE");
}
void InLIFO(Nodo *&I, int D)
{
Nodo *Nuevo = (Nodo*)malloc(sizeof(Nodo));
Nuevo -> Dat = D;
Nuevo -> Sig = I;
I = Nuevo;
}
void printlist(Nodo *I)
{
for( ;I ; I = I -> Sig)
{
printf("%d\t",I -> Dat);
}
}
void clearlist(Nodo*&I)
{
Nodo *tmp;
while(I)
{
tmp = I;
I = I -> Sig;
delete(tmp);
}
}