Write a method removeMin
that could be added to the LinkedIntList
class that removes the smallest element value from the linked list. Suppose a LinkedIntList
variable named list
stores the following elements:
[8, 4, 7, 2, 9, 4, 5, 3]
If you made the call of list.removeMin();
, the list would then store the elements:
[8, 4, 7, 9, 4, 5, 3]
If the list has more than one occurrence of the minimum value, the first occurrence is the one that should be removed. For example, [8, 10, 13, 8, 8, 14, 9, 8, 11] becomes [10, 13, 8, 8, 14, 9, 8, 11]. If the list is empty, you should throw a NoSuchElementException
.
Obey the following restrictions in your solution:
- Do not call any other methods on the
LinkedIntList
object, such as add
, remove
, or size
.
- Do not create new
ListNode
objects (though you may have as many ListNode
variables as you like).
- Do not use other data structures such as arrays, lists, queues, etc.
- Your solution should run in O(N) time, where N is the number of elements of the linked list.
Assume that you are adding this method to the LinkedIntList class (that uses the ListNode class) below.
public class LinkedIntList { public class ListNode {
private ListNode front; public int data;
... public ListNode next;
} ...
}