Advertisement
k0ske

combine nodes and sort

Nov 7th, 2022
1,170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.71 KB | None | 0 0
  1. template <typename T>
  2. void push(box<T>*& head, const T& newData) {
  3.     head = new box<T>(newData, head);
  4. }
  5.  
  6. template <typename T>
  7. void push_back(box<T>*& head, const T& newData) {
  8.     if (!head) {
  9.         push(head, newData);
  10.         return;
  11.     }
  12.     box<T>* temp = head;
  13.     while (temp->next != nullptr) {
  14.         temp = temp->next;
  15.     }
  16.     temp->next = new box<T>(newData);
  17. }
  18.  
  19. template <typename T>
  20. void insertAt(box<T>*& head, const T& newData, size_t index) {
  21.     if (!head) {
  22.         return;
  23.     }
  24.     if (index == 0) {
  25.         push(head, newData);
  26.         return;
  27.     }
  28.     box<T>* temp = head;
  29.     box<T>* prevTemp = nullptr;
  30.     for (size_t i = 0; i < index; ++i) {
  31.         if (temp == nullptr) {
  32.             return;
  33.         }
  34.         prevTemp = temp;
  35.         temp = temp->next;
  36.     }
  37.     if (prevTemp) {
  38.         prevTemp->next = new box<T>(newData, temp);
  39.     }
  40.  
  41. }
  42.  
  43. template <typename T>
  44. box<T>* combineBoxes(box<T>* sorted, box<T>* toAdd) {
  45.     if (!sorted || !toAdd) {
  46.         return nullptr;
  47.     }
  48.     box<T>* result = nullptr;
  49.     box<T>* tempSorted = sorted;
  50.     while (tempSorted != nullptr) {
  51.         push_back(result, tempSorted->data);
  52.         tempSorted = tempSorted->next;
  53.     }
  54.    
  55.     box<T>* tempToAdd = toAdd;
  56.     tempSorted = result;
  57.     while (tempToAdd != nullptr) {
  58.         size_t index = 0;
  59.         while (tempSorted != nullptr) {
  60.             if (tempSorted->data > tempToAdd->data) {
  61.                 insertAt(result, tempToAdd->data, index);
  62.                 break;
  63.             }
  64.             tempSorted = tempSorted->next;
  65.             index++;
  66.         }
  67.         tempSorted = result;
  68.         tempToAdd = tempToAdd->next;
  69.     }
  70.  
  71.     return result;
  72.  
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement