I'm trying to make a function in C to add numbers to an ordered linked list, but I've got the feeling it can be done in a lot less rows. Is there an example?
This example code does not work:
#include <stdio.h>
#include <stdlib.h>
struct listNode {
int number;
struct listNode *nextPtr;
};
typedef struct listNode LISTNODE;
typedef LISTNODE *LISTNODEPTR;
int main ()
{
LISTNODE a = {16,NULL};
LISTNODEPTR ptr = &a;
printList(&a);
insert(&ptr,23);
insert(&ptr,10);
insert(&ptr,12);
insert(&ptr,15);
printList(&a);
return 0;
}
void insert(LISTNODEPTR *list, int number){
if((**list).number > number){
printf("lol2 %d",number);
LISTNODE *newNode = malloc(sizeof(LISTNODE));
(*newNode).number = number;
(*newNode).nextPtr = (*list);
*list = newNode;
}else if((**list).nextPtr == NULL){
printf("lol %d",number);
LISTNODE *newNode = malloc(sizeof(LISTNODE));
(*newNode).number = number;
(*newNode).nextPtr = NULL;
(**list).nextPtr = newNode;
}else{
printf("other %d\n",number);
LISTNODE *listPtr = *list;
LISTNODE *listPtr1 = (*listPtr).nextPtr;
while((*listPtr1).number < number && (*listPtr).nextPtr != NULL ){
printf("%d > %d\n",(*listPtr).number , number);
listPtr = (*listPtr).nextPtr;
listPtr1 = (*listPtr).nextPtr;
}
LISTNODE *newNode = malloc(sizeof(LISTNODE));
(*newNode).number = number;
if((*listPtr).nextPtr != NULL){
(*newNode).nextPtr = listPtr1;
}else{
(*newNode).nextPtr = NULL;
}
(*listPtr).nextPtr = newNode;
}
}