Reputation: 13
I am planning to write a Java Function that takes two linked lists. Both have the same size. I want to return a new list that contains the maximum of the data found in the corresponding nodes of the two lists passed to my function.
However I am stuck in filling the new list. I came up with this:
function max2List (LinkedList list1 , LinkedList list2) {
LinkedList <int> list3 = new LinkedList<int> ();
for (ListNode p = list1.first ; p!=null; p=p.next) {
for (ListNode p = list2.first ; p!=null; p=p.next) {
if (list1.p.data > list2.p.data ) {
//return list3 here with big value
else if (list1.p.data < list2.p.data ) {
//return list3 here with big value
I don't know how to continue. I want list3 to contain the maximum values from the two lists.
Upvotes: 0
Views: 529
Reputation: 1285
def compare_lists(node_1, node_2):
while True:
if not node_1 and not node_2:
return 1
if (not node_1) ^ (not node_2):
return 0
if node_1.data != node_2.data:
return 0
node_1 = node_1.next
node_2 = node_2.next
Upvotes: 0
Reputation: 44230
Firstly, what you have written is not valid Java. Generics cannot use primitive types, such as the use of <int>
in your example. It needs to be a class e.g. <Integer>
. function
is also not a keyword.
For brevity, the following code assumes both lists are of equal size:
public static List<Integer> max2List (List<Integer> list1, List<Integer> list2)
{
List<Integer> maxValues = new LinkedList<>();
for (int i = 0; i < list1.size(); ++i)
{
// If item in list1 is larger, add it
if (list1.get(i).compareTo(list2.get(i)) > 0)
{
maxValues.add(list1.get(i));
}
else // else add the item from list2
{
maxValues.add(list2.get(i));
}
}
return maxValues;
}
Upvotes: 1