I am writing a program in C to build linked lists from scratch. However, I am getting hung-up on trying to build a link list that will automatically sort itself. By this, I mean that the nodes will automatically be placed in the correct location. My current code is putting only the first value into the list (and then exiting successfully), it isn't executing properly when trying to determine if it is greater than or less than its surrounding nodes. Please see my code below.
#include <stdio.h>
#include <stdlib.h>
typedef struct IntNode {
int data;
struct IntNode *next;
} IntNode;
typedef struct List {
IntNode *head;
} List;
IntNode *New_Node(int n);
void Print_List(List *theList);
void Free_List(List *theList);
void Add_in_Order(List *list, List *newnode);
int main()
{
int i=0;
List myList = {NULL};
for(i=1; i<=10; i++) {
IntNode *n=New_Node(rand()%20);
Add_in_Order(&myList, n);
}
Print_List(&myList);
Free_List(&myList);
return 0;
}
IntNode *New_Node(int n){
IntNode *temp;
temp = malloc(sizeof(IntNode));
temp->data = n;
return temp;
}
void Add_in_Order(List *list, List *newnode)
{
IntNode *x, *temp;
if(!list->head)
{
list->head = newnode;
return;
}
IntNode *hd;
hd = list->head;
IntNode *hd2;
hd2 = newnode->head;
for (hd = list->head; hd->next; hd = hd->next)
{
if((hd2->data) < (hd->data) && (hd2->data) >= (hd->next->data))
{
temp = hd->next;
hd->next = newnode;
newnode->head->next = temp;
return;
}
}
hd->next = newnode;
list->head->next = NULL;
}
I have not included Free_List or Print_List as they are working just fine. As you can see I am trying to place 10 random numbers into nodes into the list, sorted. But on print it is only printing the first generated number (13) which i have confirmed is (13) by simply printing it. Basically, there is something wrong with my for loop in Add_in_Order and I'm not sure what. Thank you!