Advertisement
Adrita

insertion sort using linked list

Aug 4th, 2019
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. struct linked_list
  4. {
  5. int data;
  6. struct linked_list *next;
  7. };
  8. typedef struct linked_list *node;
  9. node head=NULL;
  10.  
  11. node createnode()
  12. {
  13. node temp;
  14. temp=(node)malloc(sizeof(node));
  15. temp->next=NULL;
  16. return temp;
  17. }
  18. void insertion_sort(int value)
  19. {
  20. node temp=createnode(),p=head,prev=NULL;
  21. temp->data=value;
  22. if(p==NULL)
  23. {
  24. p=temp;
  25. head=p;
  26. return ;
  27. }
  28. else if(value>p->data)
  29. {
  30. temp->next=p;
  31. head=temp;
  32. return ;
  33. }
  34. else if(value<p->data && p->next==NULL)
  35. {
  36.  
  37. head->next=temp;
  38. return ;
  39. }
  40. else
  41. {
  42. while(p->next!=NULL)
  43. {
  44. if(p->data>value)
  45. {
  46. prev=p;
  47. p=p->next;
  48. continue;
  49. }
  50. else
  51. {
  52. temp->next=p;
  53. prev->next=temp;
  54. return ;
  55. }
  56. }
  57. if(p->data < value )
  58. {
  59. temp->next=p;
  60. prev->next=temp;
  61. return ;
  62. }
  63. else
  64. {
  65. p->next=temp;
  66. return ;
  67. }
  68.  
  69. }
  70. }
  71. void print_node()
  72. {
  73. node a;
  74. if(head==NULL)
  75. printf("empty\n");
  76. else
  77. {
  78. a=head;
  79. while(a!=NULL)
  80. {
  81. printf("%d ",a->data);
  82. a=a->next;
  83. }
  84. }
  85. printf("\n");
  86. }
  87. int main()
  88. {
  89. int n,data;
  90. node head=NULL;
  91. printf("1. add element\n2. print sorted\n3. exit\n");
  92. while(1)
  93. {
  94. scanf("%d",&n);
  95. if(n==1)
  96. {
  97. printf("new data: ");
  98. scanf("%d",&data);
  99. insertion_sort(data);
  100. }
  101. else if(n==2)
  102. {
  103. print_node();
  104. }
  105. else
  106. return 0;
  107. }
  108.  
  109. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement