logo CodeStepByStep logo

mergeUpTo

Language/Type: C++ linked lists pointers

Write a member function named mergeUpTo that could be added to the LinkedIntList class. The function accepts an integer parameter N and modifies the list by merging neighboring nodes as much as necessary so that every node in the list will have a value of at least N. For example, suppose a LinkedIntList variable named list stores the following values. The diagram shows the result of a call of list.mergeUpTo(50); on the list.

{10, 20, 30, 86, 34, 0, -2, 10, 60, 22, 15}       list.mergeUpTo(50);
     |       /    /
     |      /    /
    {60,  86,  102}                               result

Notice how the first three elements (10, 20, 30) are merged together until they hit a sum of 60, which exceeds 50; at that point, the algorithm stops merging and moves onward. The next element, 86, is already at least 50, so no merging needs to occur. Then the next five elements (34, 0, -2, 10, 60) are merged to make 102. The last two would have been merged to form 37, but there is nothing left in the list at this point, and 37 does not exceed 50, so the 37 is evicted from the list.

If we had instead made the call of list.mergeUpTo(400); on the original list, the entire contents of the list don't add up to that much, so the result would be an empty list. If the list is empty, it should remain empty after the call.

Constraints: It is okay to modify the data field of existing nodes, if you like. Do not call any member functions of the LinkedIntList. For example, do not call add, remove, or size. You may, of course, refer to the private member variables inside the LinkedIntList. Note that the list does not have a size or m_size field. Do not use any auxiliary data structures such as arrays, vectors, queues, maps, sets, strings, etc. Do not leak memory; if you remove nodes from the list, free their associated memory. Your code must run in no worse than O(N) time, where N is the length of the list. Your code must solve the problem by making only a single traversal over the list, not multiple passes.

Write the member function as it would appear in LinkedIntList.cpp. You do not need to declare the function header that would appear in LinkedIntList.h. Assume that you are adding this method to the LinkedIntList class as defined below:

class LinkedIntList {
private:
    ListNode* front;   // nullptr for an empty list
    ...
};

struct ListNode {
    int data;
    ListNode* next;
};
Member function: Write a member function that will become part of an existing class. You do not need to write the complete class.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.