I'm trying to write some basic functions in linked list and one of them is a sorted insert. I understand what it's supposed to do but it gives me a semi sorted list. I don't know where the problem is. It does the job but some of the numbers are not in the right place. So if you could find where exactly this happens, I would be grateful.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
struct node {
int data;
struct node* next;
};
struct node* sorted_insert(struct node* ptr, int data){
struct node* newNode = malloc(sizeof(struct node));
if (!newNode){
printf("something went wrong using malloc");
}
newNode -> data = data;
if(ptr->next == NULL) {
newNode -> next = ptr; //ptr is the most recent element
return newNode;
} else {
struct node* prev = ptr->next;
struct node* current = ptr;
if(prev->next == NULL){
if((current -> data) < (newNode -> data)){
newNode -> next = ptr;
return newNode;
} else {
newNode -> next = ptr->next;
ptr -> next = newNode;
return ptr;
}
} else {
while((current -> data) > data && (prev -> data) > data) {
current = prev;
prev = prev->next;
}
newNode -> next = prev;
current -> next = newNode;
return ptr;
}
}
}
struct node* insert(struct node* ptr, int data){
struct node* newNode = malloc(sizeof(struct node));
if (!newNode){
printf("something went wrong using malloc");
}
newNode -> data = data;
newNode -> next = ptr;
return newNode;
}
void print(struct node* root){
struct node* trav = root;
while(trav->next != NULL){
printf("%d\n", trav -> data);
trav = trav -> next;
}
}
int main(){
struct node *head = NULL;
head = malloc(sizeof(struct node));
if (!head){
printf("something went wrong using malloc");
}
head -> data = -1;
head -> next = NULL;
int i;
srand(time(NULL));
for(i = 0; i < 20; i++) {
head = sorted_insert(head, rand()%2000);
print(head);
printf("\n");
}
//printf("number of elements %d\n", length(head));
//print(head);
}
see sorted_insert
function
sample output:
1279
1755
1295
1983
1353
1313
1924
1635
1296
1807
1263
1257
1199
771
386
359
278
231
141
45