logo CodeStepByStep logo

chopBothSides

Language/Type: C++ linked lists pointers

Write a member function named chopBothSides that could be added to the LinkedIntList class. The function accepts an integer parameter k and removes k elements from the front of the list and k elements from the back of the list. Suppose a LinkedIntList variable named list stores the following values:

{10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110}

The call of list.chopBothSides(3); would change the list to store the following elements:

{40, 50, 60, 70, 80}

If we followed this by a second call of list.chopBothSides(1);, the list would store the following elements:

{50, 60, 70}

If the list is not large enough to remove k elements from each side, do not modify the list and throw an integer exception. If the list contains exactly 2k elements, it should become empty as a result of the call. If k is 0 or negative, the list should remain unchanged. Do not leak memory; if you remove any nodes from the list, free their associated memory.

Constraints:

  • Your code should run in no worse than O(N) time, where N is the length of the list. (You may make more than one pass over the list, but the number of passes you make can't grow as k or N grow.)
  • The LinkedIntList class has a size() member, and you are allowed to call it once in this problem. But outside of that call, do not call any other member functions of the linked list class to solve this problem. (Note: the list does not have a size or mysize data field.)
  • Do not use any auxiliary data structures such as arrays, vectors, queues, strings, maps, sets, etc.
  • Do not modify the data field of any nodes; you must solve the problem by changing the links between nodes.
  • You may not construct new ListNode objects, though you may create as many ListNode* pointers as you like.

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.