Important Notice:

Practice-It will be discontinued as of November 1st, 2024. After this date, the website will remain online for a transitional period, but login will be restricted to University of Washington NetID authentication. This marks the next phase towards the platform's full retirement. Thank you for your use and support of the application over the years.

If you are looking for an alternative, a similar tool, CodeStepByStep, was developed independently by the original author of Practice-It, and is available at codestepbystep.com**

logo Practice-It logo

trimEnds

Related Links:
Author: Marty Stepp (on 2010/12/28)

Write a method trimEnds that could be added to the LinkedIntList class. The method 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 list stores the following values:

[10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110]

The call list.trimEnds(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.trimEnds(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, throw an IllegalArgumentException. 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.

For full credit, obey the following restrictions in your solution:

  • The method should run in no worse than O(N) time, where N is the length of the list. (You can make more than one pass over the list, but you may not make N passes over the entire list.)
  • Do not call any methods of the linked list class to solve this problem. (Note that the list does not have a size field, and that you are not supposed to call its size method.)
  • Do not use auxiliary data structures such as an array, ArrayList, Queue, String, etc.
  • Do not modify the data field of any nodes; you must solve the problem by changing the links between nodes.
  • You may not create new ListNode objects, though you may create as many ListNode variables as you like.

Assume that we are adding this method to the LinkedIntList class as shown below:

public class LinkedIntList {
    private ListNode front;
    ...
}

public class ListNode {
    public int data;
    public ListNode next;
    ...
}
Type your solution here:


This is a partial class problem. Submit code that will become part of an existing Java class as described. You do not need to write the complete class, just the portion described in the problem.

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.