【问题标题】:Comparing two linked lists and returing a list with maximum values比较两个链表并返回一个具有最大值的列表
【发布时间】:2016-12-01 18:09:29
【问题描述】:

我打算编写一个带有两个链表的 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 包含两个列表中的最大值。

【问题讨论】:

  • 当你说你想要“数据的最大值......”时,你是指每个列表中的单个最大元素,还是想要每个列表中最大数据元素的更大子集?每个列表的上半部分?前 x% 的合并列表?
  • 我的意思是每个列表中要放入新列表中的单个最大元素

标签: java linked-list


【解决方案1】:

首先,您编写的不是有效的 Java。泛型不能使用原始类型,例如在您的示例中使用 &lt;int&gt;。它需要是一个类,例如&lt;Integer&gt;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;
}

【讨论】:

  • 对不起,我在第一行的错误,但我正在考虑创建一个循环,在第一个列表中找到最大值,然后将其放入一个新列表中,然后在第二个列表中找到第二个循环最大值并将其放入新列表中,基本上 list3 应该包含两个列表中的最大值
  • 您是说 list3 应该始终包含 2 个项目 - 列表 1 中最大的项目和列表 2 中最大的项目?
  • 它应该包含最大值,例如 list1 = 3->7->5->null list2 = 2->1->5->null 然后 list3 = 3->7->5- >null
  • 你现在给我的请求有冲突。您对该问题的评论表明您希望将每个列表中的单个最大元素放入一个新列表中。我已经更新了我的答案以反映这一点。那是不是你刚才描述的。如果是,您的 list3 应该是 7 -&gt; 5 -&gt; null
  • 对不起,我的意思是我刚才描述的它应该包含最大值,如 list1 = 3->7->5->null list2 = 2->1->5->null 然后 list3 = 3->7->5->null 我不应该为此创建循环吗?
【解决方案2】:
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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    • 2022-06-16
    • 2014-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多