Write a function named mergeUpTo
that accepts two parameters: a reference to a pointer to the front of a linked list, and an integer 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 variable named front
points to the front of a list storing the following values.
The diagram shows the result of a call of mergeUpTo(front, 50);
on the list.
{10, 20, 30, 86, 34, 0, -2, 10, 60, 22, 15} mergeUpTo(front, 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 mergeUpTo(front, 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 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.
Assume that you are using the ListNode
structure as defined below:
struct ListNode {
int data; // value stored in each node
ListNode* next; // pointer to next node in list (nullptr if none)
};