I'm trying to implement an insertion function to insert nodes in a linked list.(using the code written in study 50) the program appends and prepend nodes successfully but when it comes to inserting a node in the middle, it goes wrong.the program doesn't insert them at all. i am sure that the mistake is in my insertion sort.thats my code.
#include <stdio.h>
#include <stdlib.h>
#define SIZE 5
typedef struct node
{
// the value to store in this node
int n;
// the link to the next node in the list
struct node* next;
} node;
node* head = NULL;
node* last = NULL;
void insert_sorted(int i)
{
node* new_node = malloc(sizeof(node));
new_node->n = i;
new_node->next = NULL;
//if it's the first element,make the head and the last pointer point to it
if( head == NULL)
{
head = new_node;
last = new_node;
return;
}
//if it's the smallest element in the list.prepend to head;
if(head->n >= i)
{
new_node->next = head;
head = new_node;
return;
}
// if it's the largest element,append
else if(last->n <= i)
{
last->next = new_node;
last = new_node;
return;
}
// inserting an node in the middle by keeping track of each two adjacent elements;
node* ptr2;
for(node* ptr = head; ptr != NULL; ptr = ptr->next)
{
ptr2 = ptr->next;
if( ptr->n <=i && ptr2->n >= i )
{
new_node->next = ptr2;
ptr2 = new_node;
return;
}
}
}
int main(int argc, char* argv[])
{
int n;
printf("Inserting %i random ints to the list...\n", SIZE);
for (int i = 0; i < SIZE; i++)
{
n = rand() % SIZE;
insert_sorted(n);
}
printf("done!\n");
// printing out list
printf("Your list now contains ");
for (node* ptr = head; ptr != NULL; ptr = ptr->next)
{
printf("%i ", ptr->n);
}
printf("\n");
return 0;
}