logo CodeStepByStep logo

expand

Language/Type: C++ linked lists pointers

Write a member function named expand that could be added to the LinkedIntList class. The function accepts 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 LinkedIntList variable named list stores the following values:

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

The call of list.expand(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 list.expand(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 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.

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.