Here is source code of the C++ Program to demonstrate the implementation of Merge Sort using Linked.

Here is source code of the C++ Program to demonstrate the implementation of Merge Sort using Linked.

Here is source code of the C++ Program to demonstrate the implementation of Merge Sort using Linked List. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2. * C++ Program to Implement Merge Sort using Linked List
  3. */
  4. #include
  5. #include
  6. #include
  7. using namespace std;
  8. /*
  9. * Node Declaration
  10. */
  11. struct node
  12. {
  13. int data;
  14. struct node* next;
  15. };
  16. struct node* SortedMerge(node* a, node* b);
  17. void FrontBackSplit(node* source, node** frontRef, node** backRef);
  18. /* sorts the linked list by changing next pointers (not data) */
  19. void MergeSort(struct node** headRef)
  20. {
  21. node* head = *headRef;
  22. node* a;
  23. node* b;
  24. if ((head == NULL) || (head->next == NULL))
  25. {
  26. return;
  27. }
  28. FrontBackSplit(head, &a, &b);
  29. MergeSort(&a);
  30. MergeSort(&b);
  31. *headRef = SortedMerge(a, b);
  32. }
  33. /* merge the sorted linked lists */
  34. node* SortedMerge(struct node* a, struct node* b)
  35. {
  36. node* result = NULL;
  37. if (a == NULL)
  38. return b;
  39. else if (b==NULL)
  40. return a;
  41. if (a->data <= b->data)
  42. {
  43. result = a;
  44. result->next = SortedMerge(a->next, b);
  45. }
  46. else
  47. {
  48. result = b;
  49. result->next = SortedMerge(a, b->next);
  50. }
  51. return result;
  52. }
  53. /* Split the nodes of the given list into front and back halves*/
  54. void FrontBackSplit(node* source, node** frontRef, node** backRef)
  55. {
  56. node* fast;
  57. node* slow;
  58. if (source==NULL || source->next==NULL)
  59. {
  60. *frontRef = source;
  61. *backRef = NULL;
  62. }
  63. else
  64. {
  65. slow = source;
  66. fast = source->next;
  67. while (fast != NULL)
  68. {
  69. fast = fast->next;
  70. if (fast != NULL)
  71. {
  72. slow = slow->next;
  73. fast = fast->next;
  74. }
  75. }
  76. *frontRef = source;
  77. *backRef = slow->next;
  78. slow->next = NULL;
  79. }
  80. }
  81. /* print nodes in a given linked list */
  82. void printList(node *node)
  83. {
  84. while (node != NULL)
  85. {
  86. coutdata
  87. node = node->next;
  88. }
  89. }
  90. /* insert a node at the beginging of the linked list */
  91. void push(node** head_ref, int new_data)
  92. {
  93. node *new_node = new node;
  94. new_node->data = new_data;
  95. new_node->next = (*head_ref);
  96. (*head_ref) = new_node;
  97. }
  98. /* Main */
  99. int main()
  100. {
  101. node* res = NULL;
  102. node* a = NULL;
  103. push(&a, 15);
  104. push(&a, 10);
  105. push(&a, 5);
  106. push(&a, 20);
  107. push(&a, 3);
  108. push(&a, 2);
  109. MergeSort(&a);
  110. cout
  111. printList(a);
  112. return 0;
  113. }