fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4.  
  5. struct node {
  6. int data;
  7. struct node* next;
  8. };
  9.  
  10. struct node *sorted_insert(struct node *ptr, int data){
  11. struct node *newNode = malloc(sizeof(struct node));
  12. if (!newNode){
  13. printf("something went wrong using malloc");
  14. return NULL;
  15. }
  16. newNode->data = data;
  17.  
  18. if(ptr->next == NULL){//dummy node
  19. newNode -> next = ptr;
  20. return newNode;
  21. } else {
  22. if(ptr->next->next == NULL){//one node
  23. if(ptr->data < data){
  24. newNode->next = ptr;
  25. return newNode;
  26. } else {
  27. newNode->next = ptr->next;
  28. ptr->next = newNode;
  29. return ptr;
  30. }
  31. } else {
  32. struct node *prev = NULL;
  33. struct node *current = ptr;
  34. while(current->next != NULL && current->data > data) {
  35. prev = current;
  36. current = current->next;
  37. }
  38. newNode->next = current;
  39. if(prev){
  40. prev->next = newNode;
  41. } else {
  42. ptr = newNode;
  43. }
  44. return ptr;
  45. }
  46. }
  47. }
  48.  
  49. void print(struct node* root){
  50. struct node* trav = root;
  51. while(trav->next != NULL){
  52. printf("%d\n", trav -> data);
  53. trav = trav -> next;
  54. }
  55. }
  56.  
  57. int main(void){
  58. struct node *head = NULL;
  59. head = malloc(sizeof(struct node));
  60. if (!head){
  61. printf("something went wrong using malloc");
  62. return -1;
  63. }
  64.  
  65. head -> data = -1;
  66. head -> next = NULL;
  67.  
  68. srand(time(NULL));
  69. for(int i = 0; i < 20; i++) {
  70. int data = rand()%2000;
  71. printf("%d ", data);
  72. head = sorted_insert(head, data);
  73. }
  74. puts("");
  75.  
  76. //printf("number of elements %d\n", length(head));
  77. print(head);
  78. }
Success #stdin #stdout 0s 9424KB
stdin
Standard input is empty
stdout
703 1404 326 1987 1260 1774 926 1774 263 157 1727 1058 1665 179 576 457 1286 51 422 739 
1987
1774
1774
1727
1665
1404
1286
1260
1058
926
739
703
576
457
422
326
263
179
157
51