Advertisement
Guest User

Untitled

a guest
Apr 18th, 2019
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. void sortedInsert(struct Node**, struct Node*);
  2.  
  3. // function to sort a singly linked list using insertion sort
  4. void insertionSort(struct Node **head_ref)
  5. {
  6. // Initialize sorted linked list
  7. struct Node *sorted = NULL;
  8.  
  9. // Traverse the given linked list and insert every
  10. // node to sorted
  11. struct Node *current = *head_ref;
  12. while (current != NULL)
  13. {
  14. // Store next for next iteration
  15. struct Node *next = current->next;
  16.  
  17. // insert current in sorted linked list
  18. sortedInsert(&sorted, current);
  19.  
  20. // Update current
  21. current = next;
  22. }
  23.  
  24. // Update head_ref to point to sorted linked list
  25. *head_ref = sorted;
  26. }
  27.  
  28. /* function to insert a new_node in a list. Note that this
  29. function expects a pointer to head_ref as this can modify the
  30. head of the input linked list (similar to push())*/
  31. void sortedInsert(struct Node** head_ref, struct Node* new_node)
  32. {
  33. struct Node* current;
  34. /* Special case for the head end */
  35. if (*head_ref == NULL || (*head_ref)->data >= new_node->data)
  36. {
  37. new_node->next = *head_ref;
  38. *head_ref = new_node;
  39. }
  40. else
  41. {
  42. /* Locate the node before the point of insertion */
  43. current = *head_ref;
  44. while (current->next!=NULL &&
  45. current->next->data < new_node->data)
  46. {
  47. current = current->next;
  48. }
  49. new_node->next = current->next;
  50. current->next = new_node;
  51. }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement