logo CodeStepByStep logo

combineDuplicates

Language/Type: C++ linked lists pointers
Author: Marty Stepp (on 2016/12/04)

Write a function named combineDuplicates that manipulates a list of ListNode structures. The function accepts as a parameter a reference to a pointer to the front of a list, and 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 pointer named list points to the front of a list containing the following values. The diagram shows the result of a call of combineDuplicates(list); 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}       combineDuplicates(list);

{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 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.

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 (NULL if none)
}
Type your C++ solution code here:


This is a function problem. Write a C++ function as described. Do not write a complete program; just the function(s) above.

You must log in before you can solve this problem.


Log In

If you do not understand how to solve a problem or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect problems/tests, etc.), please

Is there a problem? Contact a site administrator.

© Marty Stepp, all rights reserved.