fork(2) download
  1.  
  2.  
  3. #include<iostream>
  4. #include<cstdlib>
  5.  
  6.  
  7. using namespace std;
  8.  
  9.  
  10. struct node
  11. {
  12. int info;
  13. struct node *next;
  14. };
  15.  
  16.  
  17. void push(struct node **manage,int ele)
  18. {
  19. struct node *temp=(struct node *)malloc(sizeof(struct node));
  20. temp->info=ele;
  21. temp->next=*manage;
  22. *manage=temp;
  23. }
  24.  
  25.  
  26. void display(struct node *manage)
  27. {
  28. if(manage==nullptr)
  29. cout<<"\n\n Linked list is empty!!!";
  30. else
  31. {
  32. cout<<"\n\n";
  33. while(manage!=nullptr)
  34. {
  35. cout<<' '<<manage->info;
  36. manage=manage->next;
  37. }
  38. }
  39. }
  40.  
  41. void backfrontsplit(struct node *List,struct node **fron_t,struct node **bac_k)
  42. {
  43.  
  44. struct node *slow_p=List,*fast_p=List->next;
  45. while(fast_p&&fast_p->next)
  46. {
  47. slow_p=slow_p->next;
  48. fast_p=fast_p->next->next;
  49. }
  50. *bac_k=slow_p->next;
  51. *fron_t=List;
  52. slow_p->next=nullptr;
  53. }
  54.  
  55. struct node * Merge_Linked_list_recursive(struct node *fron_t,struct node *bac_k)
  56. {
  57.  
  58. struct node *temp;
  59.  
  60. if(fron_t==nullptr&&bac_k==nullptr)
  61. return(nullptr);
  62. else if(fron_t!=nullptr&&(bac_k?fron_t->info<=bac_k->info:1))
  63. {
  64. temp=(struct node *)malloc(sizeof(struct node));
  65. temp->info=fron_t->info;
  66. temp->next=Merge_Linked_list_recursive(fron_t->next,bac_k);
  67. }
  68. else if(bac_k!=nullptr&&(fron_t?fron_t->info>bac_k->info:1))
  69. {
  70. temp=(struct node *)malloc(sizeof(struct node));
  71. temp->info=bac_k->info;
  72. temp->next=Merge_Linked_list_recursive(fron_t,bac_k->next);
  73. }
  74. return(temp);
  75. }
  76.  
  77. void Merge_sort(struct node **manage)
  78. {
  79. struct node *f,*b;
  80. struct node *head=*manage;
  81.  
  82. if(head==nullptr||head->next==nullptr)
  83. return;
  84.  
  85. backfrontsplit(head,&f,&b);
  86. Merge_sort(&f);
  87. Merge_sort(&b);
  88. *manage=Merge_Linked_list_recursive(f,b);
  89. }
  90.  
  91.  
  92.  
  93.  
  94. int main()
  95. {
  96. struct node *first=nullptr;
  97. push(&first,5);
  98. push(&first,6);
  99. push(&first,7);
  100. push(&first,8);
  101. push(&first,9);
  102. push(&first,10);
  103. display(first);
  104. Merge_sort(&first);
  105. cout<<"\n\n";
  106. display(first);
  107. return(0);
  108. }
  109.  
Success #stdin #stdout 0s 3428KB
stdin
Standard input is empty
stdout

 10 9 8 7 6 5



 5 6 7 8 9 10