#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;
void insert_sorted(int i)
{
node
* new
= malloc(sizeof(node
)); new->n = i;
new->next = NULL;
//the second pointer to keep track of linked list elements in the for loop
node* ptr2;
for(node* ptr = head ; ptr != NULL ; ptr = ptr->next )
{ ptr2 = head->next;
//if it's the first element or the smallest element in the list.prepend to head;
if( head == NULL || head->n >= i)
{
new->next = head;
head = new;
break;
}
// append at the end
else if(ptr2 == NULL && ptr->n <= i)
{
ptr2 = new;
break;
}
else if( ptr->n <=i && ptr2->n >= i )
{
new->next = ptr2;
ptr->next = new;
break;
}
}
}
int main(int argc, char* argv[])
{
printf("Inserting %i random ints to the list...\n", SIZE
); for (int i = 0; i < SIZE; i++)
{
insert_sorted
(rand() % SIZE
); }
// printing out list
printf("Your list now contains "); for (node* ptr = head; ptr != NULL; ptr = ptr->next)
{
}
return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDxzdGRsaWIuaD4KCiNkZWZpbmUgU0laRSA1Cgp0eXBlZGVmIHN0cnVjdCBub2RlCnsKICAgIC8vIHRoZSB2YWx1ZSB0byBzdG9yZSBpbiB0aGlzIG5vZGUKICAgIGludCBuOwoKICAgIC8vIHRoZSBsaW5rIHRvIHRoZSBuZXh0IG5vZGUgaW4gdGhlIGxpc3QKICAgIHN0cnVjdCBub2RlKiBuZXh0Owp9Cm5vZGU7Cgpub2RlKiBoZWFkID0gTlVMTDsKCnZvaWQgaW5zZXJ0X3NvcnRlZChpbnQgaSkKewogICAgbm9kZSogbmV3ID0gbWFsbG9jKHNpemVvZihub2RlKSk7CiAgICBuZXctPm4gPSBpOwogICAgbmV3LT5uZXh0ID0gTlVMTDsKICAgIC8vdGhlIHNlY29uZCBwb2ludGVyIHRvIGtlZXAgdHJhY2sgb2YgbGlua2VkIGxpc3QgZWxlbWVudHMgaW4gdGhlIGZvciBsb29wCi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