logo CodeStepByStep logo

expand

Language/Type: C++ linked lists pointers

Write a function named expand that manipulates a linked list represented by a chain of ListNode structures. The function accepts two parameters: a reference to a ListNode pointer to the front of the list, and an integer parameter k, and replaces each node of the list with k new nodes, each containing a fraction of the original node's value. Specifically, if the original node's value was v, each new node's value should be v / k. Suppose a variable named list points to the front of a list storing the following values:

{12, 34, -8, 3, 46}

The call of expand(list, 2); would change the list to store the following elements. Notice how 12 becomes two 6es, and 34 becomes two 17s, and -8 becomes two -4s, and so on. The value 3 doesn't divide evenly by 2, so each new element is the result of truncated integer division of 3 / 2, which yields 1. The 46 becomes two 23s.

{6, 6, 17, 17, -4, -4, 1, 1, 23, 23}

If we had instead made the call of expand(list, 3); on the original list, the list would store the following elements:

{4, 4, 4, 11, 11, 11, -2, -2, -2, 1, 1, 1, 15, 15, 15}

If the list is empty, it should remain empty after the call. If the value of k passed is 0, you should remove all elements from the list. If the value of k passed is negative, do not modify the list and instead throw an integer exception.

Constraints: Do not modify the data field of any nodes; you must solve the problem by changing links between nodes and adding newly created nodes to the list. This means that the list's original nodes must be discarded as they are replaced by the new expanded nodes your code is creating. 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.

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)
}
Function: Write a C++ function as described, not a complete program.

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.