logo Practice-It logo

takeSmallerFrom

Related Links:
Author: Robert Baxter

Write a method takeSmallerFrom that compares two lists of integers, making sure that the first list has smaller values in corresponding positions. For example, suppose the variables list1 and list2 refer to lists that contain the following values:

list1: [3, 16, 7, 23]
list2: [2, 12, 6, 54]

If the call of list1.takeSmallerFrom(list2); is made, the method will compare values in corresponding positions and move the smaller values to list1. It will find that among the first pair, 2 is smaller than 3, so it needs to move. In the second pair, 12 is smaller than 16 so it needs to move. In the third pair, 6 is smaller than 7, so it needs to move. In the fourth pair, 54 is not smaller than 23, so those values can stay where they are. Thus, after the call, the lists should store these values:

list1: [2, 12, 6, 23]
list2: [3, 16, 7, 54]

One list might be longer than the other, in which case those values stay at the end of the list. For these lists:

list3: [2, 4, 6, 8, 10, 12]
list4: [1, 3, 6, 9]

The call of list3.takeSmallerFrom(list4) should leave the lists with these values:

list3: [1, 3, 6, 8, 10, 12]
list4: [2, 4, 6, 9]

Assume that we are adding this method to the LinkedIntList class as shown below. You may not call any other methods of the class to solve this problem, you may not construct any new nodes, and you may not use any auxiliary data structures to solve this problem (such as an array, ArrayList, Queue, String, etc.). You also may not change any data fields of the nodes. You must solve this problem by rearranging the links of the lists.

    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.