fork(1) download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. #define SIZE 5
  5.  
  6. typedef struct node
  7. {
  8. // the value to store in this node
  9. int n;
  10.  
  11. // the link to the next node in the list
  12. struct node* next;
  13. }
  14. node;
  15.  
  16. node* head = NULL;
  17.  
  18. void insert_sorted(int i)
  19. {
  20. node* new = malloc(sizeof(node));
  21. new->n = i;
  22. new->next = NULL;
  23. //the second pointer to keep track of linked list elements in the for loop
  24. node* ptr2;
  25. for(node* ptr = head ; ptr != NULL ; ptr = ptr->next )
  26. { ptr2 = head->next;
  27. //if it's the first element or the smallest element in the list.prepend to head;
  28. if( head == NULL || head->n >= i)
  29. {
  30. new->next = head;
  31. head = new;
  32. break;
  33. }
  34. // append at the end
  35. else if(ptr2 == NULL && ptr->n <= i)
  36. {
  37. ptr2 = new;
  38. break;
  39. }
  40. else if( ptr->n <=i && ptr2->n >= i )
  41. {
  42. new->next = ptr2;
  43. ptr->next = new;
  44. break;
  45. }
  46.  
  47. }
  48. }
  49.  
  50. int main(int argc, char* argv[])
  51. {
  52. printf("Inserting %i random ints to the list...\n", SIZE);
  53. for (int i = 0; i < SIZE; i++)
  54. {
  55. insert_sorted(rand() % SIZE);
  56. }
  57. printf("done!\n");
  58.  
  59. // printing out list
  60. printf("Your list now contains ");
  61. for (node* ptr = head; ptr != NULL; ptr = ptr->next)
  62. {
  63. printf("%i ", ptr->n);
  64. }
  65. printf("\n");
  66.  
  67. return 0;
  68. }
Success #stdin #stdout 0s 2288KB
stdin
Standard input is empty
stdout
Inserting 5 random ints to the list...
done!
Your list now contains