logo CodeStepByStep logo

removeRange

Language/Type: C++ linked lists pointers

Write a function named removeRange that remove elements whose values are in a given range from a linked list. Your function accepts three parameters: a reference to a pointer to the front of a linked list, and a min and max as integers, and removes all elements from the list whose values are between min and max, inclusive. It should also return whether the list was modified by the call: true if it was, and false if not. Suppose a variable named front points to the front of a list that stores the following values:

{4, 2, 1, 10, 15, 8, 7, 4, 20, 36, -3, 40, 5}

The call of removeRange(front, 4, 20); would and change the list to store the following elements, and return true:

{2, 1, 36, -3, 40}

If the value of the max parameter is less than that of the min parameter, you should throw an integer exception. If the list is empty or does not contain any elements in the range of min to max, return false and leave the list unchanged.

Constraints: 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 modify the data field of any nodes; you must solve the problem by changing links between nodes. Do not leak memory; if you remove nodes from the list, free their associated memory. 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. You should make no more than one pass over 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.