Write a member function named combineDuplicates
that could be added to the LinkedIntList
class.
The function modifies the list by merging any consecutive neighboring nodes that contain the same element value into a single node whose value is the sum of the merged neighbors.
For example, suppose a LinkedIntList
variable named list
stores the following values.
The diagram shows the result of a call of list.combineDuplicates();
on the list.
The underlined areas represent the neighboring duplicate elements that are merged in the final result.
{3, 3, 2, 4, 4, 4, -1, -1, 4, 12, 12, 12, 12, 48, -5, -5} list
{3, 3, 2, 4, 4, 4, -1, -1, 4, 12, 12, 12, 12, 48, -5, -5} list.combineDuplicates();
{6, 2, 12, -2, 4, 48, 48, -10} result
If the list is empty or contains no duplicates, it should be unchanged by a call to your function.
Constraints:
It is okay to modify the data
field of existing nodes, if you like.
Do not call any methods of the LinkedIntList
class.
You may, of course, refer to the private member variables inside the LinkedIntList
.
Note that the list does not have a size
or mysize
field.
Do not construct any new ListNode
objects in solving this problem (though you may create as many ListNode*
pointer variables as you like).
Do not use any auxiliary data structures to solve this problem (no array, vector, stack, queue, string, etc).
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;
};