I am relatively new to C & pointers. I am trying to sort and then print a linked list of structs. Either I am missing a logical error or I am not fully understanding pointers. Can someone please explain to me what I am missing in this code? Thank you kindly in advance!
// *** Sort Linked List ( Merge Sort ) ***
struct address_node *newRoot;
// ptr, rearPtr, and tempRoot are also struct Pointers
newRoot = root;
root = root->next;
while (root != NULL)
{
tempRoot = root;
ptr = newRoot;
rearPtr = newRoot;
while (ptr != NULL)
{
printf("here");
if ((root->frequency) == (ptr->frequency))
{ // SPECIAL CASE: To determine read hierarchy for repeated
// Entries
if ((root->read_order) < (ptr->read_order))
{
if (ptr == newRoot)
{
root = root->next;
tempRoot->next = newRoot;
newRoot = tempRoot;
ptr = NULL;
}
else
{
root = root->next;
tempRoot->next = ptr;
rearPtr->next = tempRoot;
ptr = NULL;
}
}
}
else if ((root->frequency) > ptr->frequency)
{ // To ADD BEFORE an ENTRY
if (ptr == newRoot)
{
root = root->next;
tempRoot->next = newRoot;
newRoot = tempRoot;
ptr = NULL;
}
else
{
root = root->next;
tempRoot->next = ptr;
rearPtr->next = tempRoot;
ptr = NULL;
}
}
else if (ptr->next == NULL)
{ // if END OF LIST
root = root->next;
ptr->next = tempRoot;
ptr = NULL;
}
else
{ // SPOT NOT FOUND YET< MOVE FORWARD THROUGH LIST
rearPtr = ptr;
ptr = ptr->next;
}
}
}
// *** PRINT ***
ptr = newRoot;
if (numOut == 0)
{
while (ptr != NULL)
{
printf("0x%zx :%d\n", ptr->address, ptr->frequency);
ptr = ptr->next;
}
}
else
{
while (ptr != NULL && numOut > 0)
{
printf("0x%zx :%d\n", ptr->address, ptr->frequency);
numOut--;
ptr = ptr->next;
}
}
void print_list(const char *tag, struct address_node const *list)orvoid print_list(FILE *fp, const char *tag, struct address_node const *list)).[c] merge sort listin the SO search box. It might lead you to Using mergesort to sort linked lists, and possibly to other questions too.