有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java比较两个链表并使用最大值返回一个列表

我计划编写一个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

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


共 (2) 个答案

  1. # 1 楼答案

    首先,你写的不是有效的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;
    }
    
  2. # 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