Advertisement
Jakubowiczish

Untitled

Mar 7th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. void SplitList_v3(Node *list, Node *&list1, Node *&list2)
  2. {
  3. Node *slow = list;
  4. Node *fast = list;
  5. while(fast -> next != nullptr and fast -> next -> next != nullptr){
  6. slow = slow -> next;
  7. fast = fast -> next -> next;
  8. }
  9. list1 = slow -> next;
  10. slow -> next = nullptr;
  11. list2 = list;
  12. }
  13.  
  14. Node *MergeLists_v2(Node *list1, Node *list2)
  15. {
  16. Node *first = new Node;
  17. Node *current = first;
  18. while(list1 != nullptr or list2 != nullptr){
  19. if(list1 != nullptr and list2 == nullptr){
  20. current -> next = list1;
  21. current = current -> next;
  22. list1 = list1 -> next;
  23. }
  24. else if(list1 == nullptr and list2 != nullptr){
  25. current -> next = list2;
  26. current = current -> next;
  27. list2 = list2 -> next;
  28. }
  29. else{
  30. if(list1 -> val < list2 -> val){
  31. current -> next = list1;
  32. current = current -> next;
  33. list1 = list1 -> next;
  34. }
  35. else{
  36. current -> next = list2;
  37. current = current -> next;
  38. list2 = list2 -> next;
  39. }
  40. }
  41. }
  42. return first -> next;
  43. }
  44.  
  45. void MergeSortList(Node *&list)
  46. {
  47. if(list == nullptr or list->next == nullptr) return;
  48. Node *list1, *list2;
  49. SplitList_v3(list, list1, list2);
  50. MergeSortList(list1);
  51. MergeSortList(list2);
  52. list = MergeLists_v2(list1, list2);
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement