2016-12-01 48 views
0

我打算编写一个带有两个链接列表的Java函数。两者都有相同的尺寸。我想返回一个新列表,其中包含传递给我的函数的两个列表的相应节点中找到的最大数据。比较两个链接列表并使用最大值返回列表

但是我被困在填写新列表。我想出了这个:

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 

我不知道如何继续。我希望list3包含两个列表中的最大值。

+0

当你说你要“最大限度的数据......”你的意思是每个列表或最大的单一元素你是否想要每个列表中最大的数据元素的更大的子集?每个列表的前半部分?合并列表的前x%? – mba12

+0

我的意思是将每个列表中的单个最大元素放在一个新列表中 – GenreicITStudent

回答

0

首先,你写的是不是有效的Java。泛型不能使用原始类型,例如在您的示例中使用<int>。它需要是一个类,例如<Integer>function也不是一个关键字。

为了简便起见,下面的代码假定这两个列表大小相同:

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; 
} 
+0

对不起,我在第一行的错误,但我想创建一个循环,在第一个列表中找到最大的价值把它放在一个新的列表中,然后第二个循环在第二个列表中找到最大值并将其放入新列表中基本上list3应该包含这两个列表中的最大值 – GenreicITStudent

+0

你是说list3应该总是包含2个项目 - 列表1中的最大项目和列表2中最大的项目? – Michael

+0

它应该包含最大的值,如list1 = 3-> 7-> 5-> null list2 = 2-> 1-> 5-> null然后list3 = 3-> 7-> 5-> null – GenreicITStudent