Whats wrong with it? its supposed to sort it in ascending order. it doesn’t cause the program to crash but when I’m pretty sure theres something wrong because when I the linked list to other functions it gets stuck in an infinite loop.
#include <stdio.h>
#include <stdlib.h>
struct dataTag {
int key;
};
struct nodeTag {
struct dataTag data;
struct nodeTag *pNext;
};
typedef struct dataTag dataStructType;
typedef struct nodeTag nodeStructType;
nodeStructType *SortList(nodeStructType *pFirst)
{
nodeStructType *swap,*ptr;
if(pFirst == NULL)
return NULL;
else
{
swap = pFirst;
ptr = pFirst -> pNext;
while(ptr != NULL)
{
if(ptr -> data.key < swap -> data.key)
swap = ptr;
ptr = ptr -> pNext;
}
swap -> pNext = SortList(pFirst -> pNext);
return swap;
}
}
int main(void)
{
nodeStructType *pFirst;
/* Lets say codes exists here that makes a link list etc just to make the code short*/
pFirst = SortList(pFirst);
/*Free List*/
return 0;
}
You cant just swap nodes to sort the list. Here is a link to a program that sorts singly linked lists.
Basically the line
swap = ptr;will not work as you think. You need to reset the links appropriately to ensure that your linked list remains linked correctly.